【问题标题】:Laravel Route-Model binding doesn't work if route is defined in route group如果在路由组中定义了路由,Laravel Route-Model 绑定不起作用
【发布时间】:2018-02-20 00:39:25
【问题描述】:

我有这条路线,

Route::get('/posts/show/{post}', 'PostsController@show');

//corresponding controller method
public function show(Post $post){
  //method logic
}

当路由在 Route::group 之外定义时,这非常有效。

但这失败了;

Route::group(['domain' => '{user}.localhost.com'], function () {
...
    Route::get('/posts/show/{post}', 'PostsController@show');
...
}

错误输出;

 Argument 1 passed to App\Http\Controllers\PostsController::show() must be an instance of App\Post, string given

要查看作为参数传递的内容,我将 PostsController::show() 修改为以下内容;

public function show($post){
    return $post;
}

//it returned the subdomain part of the url.

我可以肯定地说路线组正在按预期工作,因为我有其他路线并且它们可以工作。 (只要他们不使用 Route-Model 绑定 ofc)

我发现另外 2 个帖子解决了同样的问题,但他们没有帮助我解决这个问题。

【问题讨论】:

  • public function show($user, Post $post){ ?
  • 您正在捕获两个参数(用大括号括起来),但只为一个参数腾出空间。
  • 是的!有效。 1个问题,为什么?顺便说一句谢谢
  • @Devon 捕获两个是什么意思?这是我第一次处理子域,所以如果我听起来不知情,请忽略
  • @thatoneguy 做['domain' => '{user}.localhost.com'] 意味着{user} 变成了$user 之类的参数,'/posts/show/{post}' 也变成了$post。因此,您的控制器将同时接受$user$post,但$user 是第一个参数,它是一个字符串,而您传递的是Post。所以将$user设为第一个参数,将Post $post设为第二个

标签: php laravel


【解决方案1】:

您已经创建了一个子域通配符路由,该路由接受一个参数,即{user},并且在您的路由组内,您正在接受另一个参数,即{post},如果您想使用路由模型绑定,请在适当的顺序。例如$user,$post

所以你的控制器应该看起来像

public function show($user,Post $post){
  //method logic
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2019-12-10
    • 2021-01-05
    • 2017-10-07
    • 1970-01-01
    • 2021-11-24
    • 2018-05-26
    相关资源
    最近更新 更多