DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Laravel ApiResouce name nested route placeholder

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);
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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']);
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)