Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Laravel ApiResouce name nested route placeholder

David Carr

Laravel Framework

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.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.