laravel-route-attributes
laravel-route-attributes copied to clipboard
How to use nested resources?
Hello,
I'm wondering how I can use nested resources?
The normal way is to define the deeper resources first, then define the higher resource after. But this can't be done using attributes because there is no order/priority.
Route::group(['prefix' => 'foo'], function() {
Route::resource('/bar', Foo\BarController::class);
Route::resource('/', FooController::class);
});
So: A request to /foo/bar must land in Foo\BarController. A request to /foo or /foo/(anything else than bar) must land in FooController.
Is there a way to do this?
I see this is the same issue as #130. Why was it closed?
@dusp2k
I will give you example, how I do it:
First resource:
#[ApiResource(
resource: 'categories',
only: ['index', 'show', 'store', 'update', 'destroy'],
names: 'api.admin.categories',
shallow: true
)]
class CategoryController extends ApiController
{
which gives you
GET|HEAD api/admin/categories
POST api/admin/categories
GET|HEAD api/admin/categories/{category}
PUT|PATCH api/admin/categories/{category}
DELETE api/admin/categories/{category}
Nested routes with standard CRUD actions:
#[ApiResource(
resource: 'categories.sizes',
only: ['index', 'show', 'store', 'update', 'destroy'],
names: 'api.admin.categories.sizes',
shallow: false
)]
final class SizeController extends ApiController
{
Which gives you:
GET|HEAD api/admin/categories/{category}/sizes
POST api/admin/categories/{category}/sizes
GET|HEAD api/admin/categories/{category}/sizes/{size}
PUT|PATCH api/admin/categories/{category}/sizes/{size}
DELETE api/admin/categories/{category}/sizes/{size}
Third level, what you have asked:
#[ApiResource(
resource: 'categories/{category}/sizes/sequences',
only: ['store'],
names: 'api.admin.categories.sizes.sequences',
shallow: false
)]
final class SequenceController extends ApiController
{
which will give you:
POST api/admin/categories/{category}/sizes/sequences
It works in same manner, as you would add those routes using routes/*.php
Dear contributor,
because this issue seems to be inactive for quite some time now, I've automatically closed it. If you feel this issue deserves some attention from my human colleagues feel free to reopen it.