到目前为止,我知道如何在单个参数上创建路由器模型绑定(bind),如下所示:
// RouteServiceProvider.php
$router->model('subject_slug', 'App\Subject', function($slug) {
return Subject::where('slug', $slug)->firstOrFail();
});
上面的内容可以像这样使用:
// routes.php
Route::get('/{subject_slug}', 'MenuController@showSubject');
在 Controller 中:
public function showSubject(Subject $subject) {
....
}
但有时我需要指定多个参数才能获得正确的模型。
例如,考虑以下路线:
Route::get('/{subject_slug}/{topic_slug}/', 'MenuController@showTopic');
以及相应的 Controller :
public function showTopic(Subject $subject, Topic $topic) {
....
}
但是,要获得主题
的正确模型,我需要知道主题
。例如:
// !!! 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
创建路由器模型绑定(bind),记住我需要知道它之前的Subject
参数才能获取正确的Topic
。
是否有更好的替代方法?
更新
目前我的 Controller 中的 showTopic
方法如下:
public function showTopic(Subject $subject, $topic_slug) {
$topic = Topic::where([
'subject_slug' => $subject_slug,
'slug' => $topic_slug,
])->firstOrFail();
// ...
}
并且我没有 topic_slug
的路由器模型绑定(bind)。
这按预期工作,但我想利用路由器模型绑定(bind)!
最佳答案
事实证明我的做法有点缺陷。我不必要地使用模型绑定(bind),而使用普通绑定(bind)会更好,如下所示:
$router->bind('topic_slug', function($slug, Route $route) {
$subject = $route->parameter('subject_slug');
return Topic::where([
'subject_slug' => $subject->slug,
'slug' => $slug,
])->firstOrFail();
});
此外,我之前使用的模型绑定(bind)完全错误,因为第三个函数应该是“未找到的行为”(不是用于附加逻辑)!
关于拉拉维尔 5 : How to create a router model binding on multiple parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895365/