2014-03-25 128 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]'); 
});