user8323205
user8323205

Reputation:

nested resources in laravel not worked

I want to have nested resources like that:

Route::group(['prefix' => 'manage', 'middleware' => ['role:boss']], function () 
{
   Route::resource('/articles', 'ArticleController');

   Route::group(['prefix' => '/articles', 'as' => 'articles.'], function () {
        Route::resource('/types', 'ArticleTypeController');
    });
});

But nested route for "article/type" doesn't work, I check my ArticleTypeController outside the "article" route and work.

I really confused, Everybody can help me?

and here is my controller:

class ArticleTypeController extends Controller
{

    public function index()
    {
        $types = ArticleType::all();
        return view('manage.articles.types.index')->withtypes($types);
    }
}

Upvotes: 1

Views: 495

Answers (1)

aimme
aimme

Reputation: 6818

Route::group(['prefix' => 'manage', 'middleware' => ['role:boss']], function () 
{
   Route::get('articles/types', 'ArticleTypeController@articleTypeMethod');

   Route::resource('articles', 'ArticleController');    
   Route::resource('articles.types', 'ArticleTypeController');
});

for nested resources use articles.types. plural naming is good. now that manage/articles and manage/articles/1/types will work.

If you want to put a custom route, put it above the resource route if the controller has been used as a resource. see the articles/types [GET] route which maps to ArticleTypeController's articleTypeMethod. now this way http://localhost.com/manage/articles/types should work

here is the 5.1 documentation and it has been removed from documentation of 5.5. but have a look at what Taylor said about it here

it's not recommended on REST to use index function for articles/types, a nested resources index method is used like articles/{id}/types. for articles/types you need to create a new method.

but if you still want to do it like that. just make it like this

Route::group(['prefix' => 'manage', 'middleware' => ['role:boss']], function () 
{
   Route::get('articles/types', 'ArticleTypeController@index');

   Route::resource('articles', 'ArticleController');    
   Route::resource('articles.types', 'ArticleTypeController', ['except' => ['index']]);
});

Upvotes: 1

Related Questions