2014-06-24 77 views
5

我在Laravel項目中一直使用RESTful controllers。通過包括:路由模型綁定可以與RESTful控制器一起使用嗎?

Route::controller('things', 'ThingController') 
在我的routes.php文件

,我可以定義功能ThingController,如:

public function getDisplay($id) { 
    $thing = Thing::find($id) 
    ... 
} 

,以便獲取URL」 ......事情/顯示/ 1" 將自動成爲指向控制器功能。這看起來非常方便,迄今爲止我一直在爲我工作。

我注意到我的很多控制器功能都是從網址獲得一個id模型開始的,而且我認爲能夠使用route model binding替代我這樣做會很好。所以,我在我的routes.php文件更新到

Route::model('thing', 'Thing'); 
Route::controller('things', 'ThingController') 

,改變了ThingController功能

public function getDisplay($thing) { 
    ... 
} 

我以爲這會神奇的工作,我想它的方式(如一切我到目前爲止已經試過在Laravel有),但不幸的是,當我嘗試在函數中使用$thing時,我得到「嘗試獲取非對象的屬性」。這是應該能夠工作,我剛剛做錯了,或者可以路由模型綁定只能使用routes.php顯式命名的路由?

回答

4

如果你不與URI路徑,方法名和剛工作只有showeditupdate方法介意的話,可以使用Resource Controller生成URI字符串,它可以定義模型綁定。

routes.php變化

Route::model('things', 'Thing'); 
Route::resource('things', 'ThingController'); 

可以使用php artisan routes命令來查看所有的URI

$ artisan routes | grep ThingController 
GET|HEAD things    | things.index    | [email protected] 
GET|HEAD things/create   | things.create    | [email protected] 
POST things     | things.store    | [email protected] 
GET|HEAD things/{things}  | things.show    | [email protected] 
GET|HEAD things/{things}/edit | things.edit    | [email protected] 
PUT things/{things}   | things.update    | [email protected] 
PATCH things/{things}   |       | [email protected] 

之後,你可以威脅參數爲Thing對象,而無需顯式指定的路線。

/** 
* Display the specified thing. 
* 
* @param Thing $thing 
* @return mixed 
*/ 
public function show(Thing $thing) 
{ 
    return $thing->toJson(); 
} 

如果您要訪問[email protected],通過你的模型ID和Laravel將自動檢索它。

http://example.com/things/1

{"id":1,"type":"Yo!"} 
1

您可以使用路線:資源,並仍然提供其他方法。將您需要的路線放在特定的Route::resource線路之前。 例如:

Route::model('things', 'Thing'); 
Route::get('things/{things}/owner', '[email protected]'); 
Route::resource('things', 'ThingController'); 

然後在您的控制器中創建相應的方法。

public function getOwner($things) { 
    return Response::json($things->owner()->get()); 
} 

這是Laravel 4的官方文檔。2個文檔:

來源:http://laravel.com/docs/controllers#resource-controllers

添加其他路由爲了資源控制器

如果有必要爲你額外的路由添加到超過默認資源路徑的資源控制器,你應該定義之前,這些路由您致電Route::resource

Route::get('photos/popular'); 
Route::resource('photos', 'PhotoController'); 
相關問題