Laravel 5: Route model binding in a group

坚强是说给别人听的谎言 提交于 2019-12-14 02:49:57

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/30220617/laravel-5-route-model-binding-in-a-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!