Laravel 5.2路由模型绑定 [英] Laravel 5.2 route model binding
问题描述
Laravel有一个有关路由模型绑定的文档,可以在此处.但是,没有关于这种情况的示例:
Laravel has a documentation regarding route model binding which could be found here. But there is no example with regards to this kind of scenario:
Route::get('search/', 'ArticleController@search');
如何隐式将模型绑定到路由中?我知道我可以直接在控制器的方法上做类似的事情.
How to I implicitly bind a model into the route? I know I could do something like this directly on the controller's method.
public function search(Model $model) {
// some code here
}
但是我只是好奇如何在路线上做到这一点.
But I'm just curious on how to do it on the routes instead.
我正在采用这种方法
Route::get('search/{article}', function(ArticlesModel $articlesModel) {
// this should be calling 'ArticleController@search'
});
谢谢!
推荐答案
由于您的变量名为$model
,因此Laravel会在网址中查找通配符段,写为{model}
:
Because your variable is called $model
, Laravel will look for a wildcard segment of the url written as {model}
:
在routes.php中:
In routes.php:
Route::get('search/{article}', 'ArticleController@search');
在控制器中:
function search(Article $article) {
//$article is the Article with the id from {article}, ie. articles/2 is article 2
}
编辑...您建议的方式实际上没有任何意义.那只是一个额外的步骤,仅使用"ArticleController@search"
可以完全跳过该步骤.我认为这段代码可以运行,尽管我不建议这样做:
Edit... the way that you are suggesting doesn't really make sense. That would just be an extra step that is skipped entirely by just using "ArticleController@search"
. I think this code would function although I don't recommend it:
Route::get('search/{article}', function(Article $article)
{
$controller = App::make(ArticleController::class);
return App::call([$controller, 'search'], compact('article'));
}
这篇关于Laravel 5.2路由模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!