Laravel 5.2 路由模型绑定

Laravel 5.2 route model binding

Laravel 有一个关于路由模型绑定的文档,可以找到 here。但是没有关于这种情况的例子:

Route::get('search/', 'ArticleController@search');

如何将模型隐式绑定到路由中?我知道我可以直接在控制器的方法上做这样的事情。

public function search(Model $model) {
    // some code here
}

但我只是好奇如何在路线上进行。

我喜欢这种方法

Route::get('search/{article}', function(ArticlesModel $articlesModel) {
    // this should be calling 'ArticleController@search'
});

谢谢!

因为您的变量名为 $model,Laravel 将查找 url 的通配符段,写为 {model}:

在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" 就可以完全跳过。我认为这段代码会起作用,尽管我不推荐它:

Route::get('search/{article}', function(Article $article)
{
    $controller = App::make(ArticleController::class);
    return App::call([$controller, 'search'], compact('article'));
}

routes.php

Route::get('search/{article}', 'ArticleController@search');

ArticleController.php

public function search(Model $article) {
    // some code here
}