So I writing a simple app that has nested resources: posts and comments. Naturally, posts are parents, comments are children, related each one to one post. Simple enough. Now I want comments index (and creation, POST) page to live at posts/{post_id}/comments, update (PUT) to live at /posts/{post_id}/comments/{comment_id}. So I tried this:
Route::resource('posts', 'PostsController');
Route::group(array('prefix' => 'posts/{post_id}'), function() {
Route::resource('comments', 'CommentsController');
});
But it won't work since the route name is registered as posts.{post_id}.comments.create. Basically the post_id placeholder is counted as part of the route and it's not neat. Any way of doing this nicely or should I just write routes one by one and get rid of the group/Route::resource/prefix thing?
You can use nested resources like this;
Route::resource('posts', 'PostsController');
Route::resource('posts.comments', 'CommentsController');
When you php artisan routes you will see your new routes;
+--------+-------------------------------------------------+------------------------+------------------------------------+----------------+---------------+
| Domain | URI | Name | Action | Before Filters | After Filters |
+--------+-------------------------------------------------+------------------------+------------------------------------+----------------+---------------+
| | GET|HEAD posts | posts.index | PostsController@index | | |
| | GET|HEAD posts/create | posts.create | PostsController@create | | |
| | POST posts | posts.store | PostsController@store | | |
| | GET|HEAD posts/{posts} | posts.show | PostsController@show | | |
| | GET|HEAD posts/{posts}/edit | posts.edit | PostsController@edit | | |
| | PUT posts/{posts} | posts.update | PostsController@update | | |
| | PATCH posts/{posts} | | PostsController@update | | |
| | DELETE posts/{posts} | posts.destroy | PostsController@destroy | | |
| | GET|HEAD posts/{posts}/comments | posts.comments.index | CommentsController@index | | |
| | GET|HEAD posts/{posts}/comments/create | posts.comments.create | CommentsController@create | | |
| | POST posts/{posts}/comments | posts.comments.store | CommentsController@store | | |
| | GET|HEAD posts/{posts}/comments/{comments} | posts.comments.show | CommentsController@show | | |
| | GET|HEAD posts/{posts}/comments/{comments}/edit | posts.comments.edit | CommentsController@edit | | |
| | PUT posts/{posts}/comments/{comments} | posts.comments.update | CommentsController@update | | |
| | PATCH posts/{posts}/comments/{comments} | | CommentsController@update | | |
| | DELETE posts/{posts}/comments/{comments} | posts.comments.destroy | CommentsController@destroy | | |
+--------+-------------------------------------------------+------------------------+------------------------------------+----------------+---------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With