Don*_*nic 7 php laravel-4 laravel-routing
我一直在Laravel项目中使用RESTful控制器.包括:
Route::controller('things', 'ThingController')
Run Code Online (Sandbox Code Playgroud)
在我的routes.php中,我可以在其中定义函数ThingController:
public function getDisplay($id) {
$thing = Thing::find($id)
...
}
Run Code Online (Sandbox Code Playgroud)
因此,GETting URL"... things/display/1"将自动定向到控制器功能.这看起来非常方便,到目前为止我一直很好.
我注意到我的许多控制器函数都是从url中通过id获取模型开始的,我认为能够使用路由模型绑定为我做这件事会很好.所以我将routes.php更新为
Route::model('thing', 'Thing');
Route::controller('things', 'ThingController')
Run Code Online (Sandbox Code Playgroud)
并将ThingController功能更改为
public function getDisplay($thing) {
...
}
Run Code Online (Sandbox Code Playgroud)
我认为这会神奇地按照我想要的方式工作(就像我在Laravel迄今为止尝试的其他所有东西一样)但不幸的是,当我尝试$thing在函数中使用时,我得到"试图获得非对象的属性" .这是应该能够工作的东西吗?我刚刚做错了,或者路由模型绑定只适用于在routes.php中明确命名的路由?
如果你不与URI路径,方法名介意,只是只工作show,edit和update方法,你可以用资源控制器来生成URI字符串,它可以定义模型绑定.
在routes.php改变
Route::model('things', 'Thing');
Route::resource('things', 'ThingController');
Run Code Online (Sandbox Code Playgroud)
您可以使用php artisan routes命令查看所有URI
$ artisan routes | grep ThingController
GET|HEAD things | things.index | ThingController@index
GET|HEAD things/create | things.create | ThingController@create
POST things | things.store | ThingController@store
GET|HEAD things/{things} | things.show | ThingController@show
GET|HEAD things/{things}/edit | things.edit | ThingController@edit
PUT things/{things} | things.update | ThingController@update
PATCH things/{things} | | ThingController@update
Run Code Online (Sandbox Code Playgroud)
之后,您可以将参数威胁参数作为Thing对象而无需显式名称路由
/**
* Display the specified thing.
*
* @param Thing $thing
* @return mixed
*/
public function show(Thing $thing)
{
return $thing->toJson();
}
Run Code Online (Sandbox Code Playgroud)
如果要访问ThingController@show,请传递您的模型ID,Laravel将自动检索它.
http://example.com/things/1
{"id":1,"type":"Yo!"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5458 次 |
| 最近记录: |