我在Laravel项目中一直使用RESTful controllers。通过包括:

Route::controller('things', 'ThingController')

在我的routes.php中,我可以在ThingController中定义函数,如下所示:
public function getDisplay($id) {
    $thing = Thing::find($id)
    ...
}

因此获取网址“... things/display/1”将自动定向到 Controller 功能。这似乎很方便,到目前为止对我来说一直很好。

我注意到我的许多 Controller 功能都是从URL上的id获取模型开始的,我认为能够使用route model binding代替我来做会很好。所以我将route.php更新为
Route::model('thing', 'Thing');
Route::controller('things', 'ThingController')

并将ThingController函数更改为
public function getDisplay($thing) {
    ...
}

我以为这可以按我想要的方式神奇地工作(就像到目前为止我在Laravel中尝试过的所有其他方式一样),但是不幸的是,当我尝试在函数中使用$thing时,我得到“试图获取非对象的属性”。这是应该可以工作的东西,我做错了吗,还是可以仅通过在route.php中显式命名的路由来进行路由模型绑定(bind)?

最佳答案

如果您不介意URI路径,方法名称并且仅使用showeditupdate方法,则可以使用Resource Controller生成可以定义模型绑定(bind)的URI字符串。

routes.php中更改为

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

您可以使用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

之后,您可以威胁参数作为Thing对象,而无需显式命名路由。
/**
 * Display the specified thing.
 *
 * @param  Thing  $thing
 * @return mixed
 */
public function show(Thing $thing)
{
    return $thing->toJson();
}

如果您想访问ThingController@show,请传递您的模型ID,Laravel会自动检索它。
http://example.com/things/1
{"id":1,"type":"Yo!"}

10-04 22:56
查看更多