【问题标题】:Laravel 5: Route model binding in a groupLaravel 5:组中的路由模型绑定
【发布时间】:2015-07-25 01:59:15
【问题描述】:

我在RouteServiceProvider中做了一个Route模型绑定:

public function boot(Router $router)
    {
        parent::boot($router);

        $router->model('article', 'App\Article');
    }

我的路线组:

Route::group(['prefix' => 'articles'], function(){
  //some routes ....

  Route::group(['prefix' => '{article}'], function(){
    Route::get('', [
      'as' => 'article.show',
      'uses' => 'ArticlesController@show'
    ]);

    Route::get('comments', [
       'as' => 'article.comments',
       'uses' => 'ArticlesController@comments'
    ]);
  });
});

/articles/666 完美运行

/articles/666/commentsshow me Http not found 异常。

【问题讨论】:

    标签: laravel binding model routes


    【解决方案1】:

    我能够重新创建此问题,但前提是我的数据库中没有 id 为 666 的文章。

    奇怪的是,当我没有设置路由绑定时,我并没有遇到这个问题。

    尝试创建 id 为 666 的文章或将 id 更改为您拥有的文章,它应该可以工作。如果没有,您可能有另一条路线覆盖这条路线。运行命令php artisan route:list 以获取所有路线的列表。如果您正在缓存路由,请务必同时重新生成缓存。

    【讨论】:

    • 我真的不明白为什么? OP 已经在组前缀中绑定了文章,并说/articles/666 工作正常。
    • 666 只是一个例子,它可能是另一个 id,仍然无法正常工作
    • 这很奇怪,您显示的代码对我来说非常有效(只要我在数据库中有一篇带有我尝试的 id 的文章)。问题一定出在其他地方。
    【解决方案2】:

    使用您的路由,您可以将模型直接注入到动作中:

    // ArticlesController.php
    ...
    public function show(Article $article) {
        return response()->json($article);
    }
    

    但请记住,您需要使用“绑定”中间件组来确保模型从路由中隐式获取。 因此,例如在您的路线配置中:

    Route::middleware('bindings')->group(function() {
        Route::group(['prefix' => 'articles'], function(){
            Route::group(['prefix' => '{article}'], function(){
                Route::get('', [
                    'as' => 'article.show',
                    'uses' => 'ArticlesController@show'
                ]);
    
                Route::get('comments', [
                    'as' => 'article.comments',
                    'uses' => 'ArticlesController@comments'
                ]);
            });
        });
    });
    

    这似乎没有很好的记录。

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2015-07-02
      • 1970-01-01
      • 2021-05-24
      • 2016-06-04
      • 2018-12-17
      相关资源
      最近更新 更多