Hello Geek, We will learn How to Get the Current Route Name in Laravel in this short article. The route name will be obtained from the Controller, Middleware, and Blade File. Laravel provides some methods for obtaining the current route name.
Laravel allows you to define the route as well as the name of the route. You can use that route name anywhere you need it, such as a controller or a blade file. You must use the route() function and pass the route name as an argument to it. It will return the route with that name. It’s a very simple and useful method for obtaining and establishing a route.
Get route name in Blade View
In some cases, you need to display the route name in the Blade files like the active nav link and some other requirements.
{{ Route::currentRouteName() }}
Get route name in Laravel Controller
You can get the route name in Laravel Controller. You can see the following code for the get current route name in Laravel Controller.
public function getRouteName(Request $request){
$routeName = $request->route()->getName();
// or
$routeName = request()->route()->getName();
return $routeName;
}
Get route name in Laravel Middleware
public function handle($request, Closure $next) {
$routeName = $request->route()->getRouteName();
echo $routeName;
}
I hope in this short article you will learn How to Get the Current Route name in laravel.