Laravel 5: Route model binding in a group

2019-08-15 18:30发布

I made a Route model binding in the RouteServiceProvider:

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

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

My route group:

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 works perfectly

/articles/666/comments show me Http not found exception.

2条回答
成全新的幸福
2楼-- · 2019-08-15 18:42

I was able to recreate this issue but only when I did not have an article with id of 666 in the database.

Strangely enough, I didn't come across that issue when I did not have my route binding setup.

Try creating an article with id of 666 or changing the id to an article you do have and it should work. If it does not, you may have another route overriding this one. Run the command php artisan route:list to get a list of all your routes. If you are caching routes, be sure to regenerate the cache as well.

查看更多
爷的心禁止访问
3楼-- · 2019-08-15 18:45

Using your routing you can inject the model directly into the action:

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

But bear in mind that you need to use the 'bindings' middleware group to ensure that the model gets implicitly from the route. So eg in your routes config:

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'
            ]);
        });
    });
});

This is not something that appears well documented.

查看更多
登录 后发表回答