2014-03-25 90 views
0

我想通过url传递用户名。Laravel 4前缀变量路由

site.tld/{username}/account 

所以我在这里有这个条目我的路线

Route::group(array('prefix' => '{username}'), function($username) 
{ 
    $user = User::whereUsername($username)->first(); 
    if(!is_null($user)) 
    { 
     Route::get('portfolio', '[email protected]'); 
     Route::get('profile', '[email protected]'); 
     .... 
    } 
} 

我碰到下面的错误。

Object of class Illuminate\Routing\Router could not be converted to string 

我在做什么错?

回答

1

Route::group()不工作方式相同路线::()的方法,闭包是路由上市过程中执行的,什么是传递给它的是路由器,而不是你的参数:

Route::group(array('prefix' => '{username}'), function($router) { ... }); 

所以你基本上是这样做的:

$user = User::whereUsername($router)->first(); 

就是为什么它说,

Object of class Illuminate\Routing\Router could not be converted to string 

但是你可以使用一个过滤器:

Route::filter('age', function($route, $request) 
{ 
    if (! User::whereUsername($route->parameter('username'))->first()) 
    { 
     App::abort(404); 
    } 
}); 

Route::group(array('prefix' => '{username}', 'before' => 'age'), function($username) 
{ 
    Route::get('portfolio', '[email protected]'); 
    Route::get('profile', '[email protected]'); 
});