Home » Laravel » How to Get Route Name in Laravel

How to Get Route Name in Laravel

Every route in Laravel can have a name, which you can use to create URLs in your controllers with the route() helper. Sometimes you may want to find the current route name or a name of a route for a specific action.

In this short article, we’ll explore how to get route name in Laravel for both cases as well as how to create a URL for an action without using the route name.

How to Find Route Name in Laravel

1. The Current Rote Name

The simplest way to get the current route name is to use the Route facade and the current() method. For example:

use Illuminate\Support\Facades\Route; $currentRoute = Route::current();

Once you have the current route, you can fetch its name using the getName() method:

$name = $currentRoute->getName();

If you have an instance of Illuminate\Http\Request, you can get the route name without using the Route facade:

$request->route()->getName();

2. The Route Name for an Action

If you want to create a URL to redirect to a specific action in a controller, don’t need to use the route name. You can simply use the action() helper. For instance, to create a URL for the index action in the ExampleController use this code:

$url = action([ExampleController::class, "index"]);

The route should be configured for this action but the route name is not required.

However, if you still want to get the route name for an action in Laravel, is not very difficult. You can use the Route facade to get the RoutesCollection and use it to find the desired action by its method name and class name.

Previously, we used the following string syntax to configure routes in routes/web.php:

"Namespace\ControllerName@methodName" //regular controller "Namespace\ControllerName" //invokable controller

Nowadays, Laravel support a more fluent and convenient syntax, but it still stores actions in the way described above. So you can format this string for your action and use the getByAction() method in the RoutesCollection. Once you have an instance of a route, you can find out its name by calling the getName() method.

use Illuminate\Support\Facades\Route; class RouteUtils { public static function getRouteNameFor( string $controllerName, string $methodName ): string { $routesCollection = Route::getRoutes(); if ($methodName !== "__invoke") { $action = $controllerName . "@" . $methodName; } else { $action = $controllerName; } $route = $routesCollection->getByAction($action); if (null == $route) { throw new \RuntimeException("Can`t find route for $action"); } $name = $route->getName(); if (null == $name) { throw new \RuntimeException( "Route for action $action does not have a name" ); } return $name; } }

Example of usage:

RouteUtils::getRouteNameFor(ExampleController::class, "index"); // example

Wrapping Up

In this short article, you have learned how to get route name in Laravel for the current request or a specific route.

Your Reaction

Leave a Comment