Laravel 5:如何在多个参数上创建路由器模型绑定

时间:2015-11-24 13:48:22

标签: laravel routing laravel-5 laravel-5.1 laravel-routing

到目前为止,我知道如何在单个参数上创建路由器模型绑定,如下所示:

// RouteServiceProvider.php
$router->model('subject_slug', 'App\Subject', function($slug) {
     return Subject::where('slug', $slug)->firstOrFail();
});

以上可以像这样使用:

// routes.php
Route::get('/{subject_slug}', 'MenuController@showSubject');

在控制器中:

public function showSubject(Subject $subject) {
   ....
}

但有时我需要指定多个参数才能获得正确的模型。

例如,请考虑以下路线:

Route::get('/{subject_slug}/{topic_slug}/', 'MenuController@showTopic');

和相应的控制器:

public function showTopic(Subject $subject, Topic $topic) {
   ....
}

但要获得Topic的正确模型,我需要知道Subject。例如:

// !!! Invalid laravel code !!!
$router->model('topic_slug', 'App\Topic, function($subject_slug, $topic_slug) {
     // ERROR: $subject_slug is obviously not defined!
     return Topic::where([
        'subject_slug' => $subject_slug,
        'slug' => $topic_slug,
     ])->firstOrFail();
});

如何为Topic制作路由器模型绑定时要注意我需要知道前面的Subject参数才能获取正确的Topic

还有其他更好的方法吗?

更新

目前我的控制器中的showTopic方法是这样的:

public function showTopic(Subject $subject, $topic_slug) {
   $topic = Topic::where([
               'subject_slug' => $subject_slug,
               'slug' => $topic_slug,
            ])->firstOrFail();
   // ...
}

我没有topic_slug的路由器模型绑定。 这可以按预期工作,但我想利用路由器模型绑定!

1 个答案:

答案 0 :(得分:2)

事实证明我做这件事的方式有点瑕疵。当我使用模型绑定时,我会更好地使用正常的绑定,如下所示:

$router->bind('topic_slug', function($slug, Route $route) {
     $subject = $route->parameter('subject_slug');
     return Topic::where([
        'subject_slug' => $subject->slug,
        'slug' => $slug,
     ])->firstOrFail();
});

此外我之前使用的模型绑定完全错误,因为第3个函数应该是“未找到的行为”(不适用于其他逻辑)!