Loading...

Laravel ApiResouce name nested route placeholder

David Carr

2 min read - 11th Jan, 2024

Laravel routes nested placeholders

Table of Contents

When using an ApiResource that has more than one placeholder it may seem tricky to figure out how to name the placeholder used.

For example, take this route:

Route::apiResource('users.tenant', UsersController::class);

This produces these routes

Now let's say we wanted to use {team} instead of {tenant}

How would you do it?

You may be tempted to drop ApiResource routes and manually create the routes so it's easy to name the placeholders such as:

Route::get('users/{user}/tenant', [UsersController::class, 'index'])->name('users.tenant.index'); 
Route::post('users/{user}/tenant', [UsersController::class, 'store'])->name('users.tenant.store');
Route::get('users/{user}/tenant/{team}', [UsersController::class, 'show'])->name('users.tenant.show');
Route::match(['put', 'patch'], 'users/{user}/tenant/{team}', [UsersController::class, 'update'])->name('users.tenant.update'); 
Route::delete('users/{user}/tenant/{team}', [UsersController::class, 'destroy'])->name('users.tenant.destroy');

While this will work, it would be better if an ApiResouce can still be used.

It can, instead of manually creating the routes we can rename the placeholders in two ways.

Route Parameter methods

1) Using parameter()

Route::apiResource('users.tenant', Users::class)
    ->parameter('tenant', 'team');

By setting parameter we can set the name of the existing placeholder and give it a new name.

2) use parameters()

Route::apiResource('users.tenant', Users::class)
->parameters([
    'users' => 'author',
    'tenant' => 'team'
]);

When you want to name more than one placeholder use parameters and pass in an array.

In this case, I've renamed users to author and tenant to team

Remember when setting the first placeholder, it has to match the route name. In this case users. If user was set the {user} placeholder would not be changed.

With either option, you can rename the placeholders whilst still using ApiResource This helps keep your routes file clean.

1 comments
Add a comment