如何在 Laravel 中通过路由名称获取带有命名空间的路由?

How to get the route with namespace by route name in Laravel?

我有如下路线

Route::group(['prefix' => '/entry', 'namespace' => 'acme'], function() {

    Route::get('add', [
        'uses' => 'EntriesController@add',
        'as' => 'entry.add'
    ]);

});

如果在我的代码中某处我只知道路线名称,如何获得完整的路线('acme\EntriesController@add')? 像

$route = Route::getRoute('entry.add');

首先,这是通过名称获取路由对象的方法:

$route = Route::getRoutes()->getByName('route.name');

并且路由对象有方法getActionName(),所以:

echo Route::getRoutes()->getByName('entry.add')->getActionName();

在这里,我创建了供我使用的全局函数。

例如:

$routes = getRouteByName('role.add.form');

它将 return 响应如下:

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
)

下面是全局创建的函数:

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;
    }
}
}