Adding a Custom Attribute to a Route in Laravel

Posted on Updated on Laravel by Gergő D. Nagy

Laravel’s routing system is a clean and powerful tool. However, in some cases, we might need to extend its “attribute bag” with some custom value.

First of all, let’s define a route group that contains the routes we want to “extend”. Then we will take a look at how can we get the custom attribute from the current route instance.

Route::as('admin.')->prefix('admin')->group(['key' => 'value'], function ($router) {
    $router->get('dashboard', DashboardController::class)->name('dashboard');
    $router->get('profile', ProfileController::class)->name('profile');
})->middleware('auth');

This is a normal route definition. But you can see the first parameter of the group method:

['key' => 'value']

This will be added to the route’s action array. So you can obtain it by using a Request instance.

$request->route()->action['key']; // 'value'

Why is it good? Because you can add custom parameters to your route without any effort. You can specify a class that you want to use for some specific routes and in their controllers without explicitly defining it in the controllers. It really can have many cases where you can use this approach. Not a big deal, yet it can be very useful.

Need a web developer? Maybe we can help, get in touch!