Reputation: 723
I have a route as following
Route::group(['prefix' => '/entry', 'namespace' => 'acme'], function() {
Route::get('add', [
'uses' => 'EntriesController@add',
'as' => 'entry.add'
]);
});
How to get a complete route ('acme\EntriesController@add') if somewhere in my code I only know the route name? Something like
$route = Route::getRoute('entry.add');
Upvotes: 3
Views: 2232
Reputation: 224
Here, I have created global functions for my use.
For Example:
$routes = getRouteByName('role.add.form');
it will return response like below:
Array
(
[uri] => roles/addrole
[name] => role.add.form
[prefix] =>
[action] => Array
(
[middleware] => Array
(
[0] => web
)
[domain] => admin.local.com
[uses] => App\Http\Controllers\Admin\AccessControlController@create
[controller] => App\Http\Controllers\Admin\AccessControlController@create
[namespace] => App\Http\Controllers\Admin
[prefix] =>
[where] => Array
(
)
[as] => role.add.form
)
[action_method] => create
[action_name] => App\Http\Controllers\Admin\AccessControlController@create
[domain] => admin.local.com
)
Below are the functions created globally:
if(!function_exists('getRoutes')){
function getRoutes(){
$routeCollection = Route::getRoutes();
$routes = [];
foreach ($routeCollection as $route) {
$routes[] = [
'uri' => $route->uri,
'name' => $route->getName(),
'prefix' => $route->getPrefix(),
'action_method' => $route->getActionMethod(),
'action_name' => $route->getActionName(),
];
}
return $routes;
}
}
/**
* @param string $name pass route name as parameter
* @param string $param pass the element from the route instance
* @return return all data of route by default or value when second parameter passed
* [uri,name,prefix,action_method,action_name]
* **/
if(!function_exists('getRouteByName')){
function getRouteByName($name,$param = null){
$route = Route::getRoutes()->getByName($name);
$route_data = [
'uri' => $route->uri,
'name' => $route->getName(),
'prefix' => $route->getPrefix(),
'action' => $route->getAction(),
'action_method' => $route->getActionMethod(),
'action_name' => $route->getActionName(),
'domain' => $route->getDomain(),
];
if(!empty($param)){
return $route_data[$param];
}
else{
return $route_data;
}
}
}
Upvotes: 1
Reputation: 152870
First, here's how you get a route object by it's name:
$route = Route::getRoutes()->getByName('route.name');
And the route object has the method getActionName()
, so:
echo Route::getRoutes()->getByName('entry.add')->getActionName();
Upvotes: 6