How to get the current route name in Laravel?

by darrion.kuhn , in category: PHP Frameworks , 9 months ago

How to get the current route name in Laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 3 months ago

@darrion.kuhn 

In Laravel, you can use the Route::currentRouteName() method to get the current route name. This method returns the name of the route as a string.


Here is an example of how you can use it in a controller or a view:

1
2
3
$routeName = Route::currentRouteName();

echo "The current route name is: $routeName";


Alternatively, you can use the Route::getCurrentRoute() method to get an instance of the IlluminateRoutingRoute class, which has a getName() method that you can use to get the name of the current route.

1
2
3
4
$route = Route::getCurrentRoute();
$routeName = $route->getName();

echo "The current route name is: $routeName";


Note that the current route name is only available if the route has a name. To give a route a name, you can use the name method when defining the route in your routes file:

1
Route::get('/home', 'HomeController@index')->name('home');


You can also pass a string as an argument to the name method to specify a custom name for the route.