拉拉维尔 5 : How to create a router model binding on multiple parameters

标签 laravel routes laravel-5 laravel-5.1 laravel-routing

到目前为止,我知道如何在单个参数上创建路由器模型绑定(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/

相关文章:

laravel - 如何使用 docker 容器从主机运行 artisan 命令

ruby-on-rails - 在 Rails 3.1 中使用 rspec 测试嵌套资源 Controller

php - 如何在ajax URL路由中添加变量

php - Laravel 根据 groupBy 获取结果计数

php - 检索多对多关系。拉维尔

laravel - 在 Laravel 中获取 Paypal 付款详细信息时出现 403 错误

php - Laravel 在非 Eloquent 模型上使用 ->lists()

php - Laravel 邮件附件超时

laravel 5.7 如何将 Controller 的请求传递给模型并保存

linux - archlinux、KVM VPS 上的 PPTP 服务器,客户端从未收到包