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

时间:2015-01-03 11:02:04

标签: php laravel laravel-4

我的路线如下

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

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

});

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

这样的东西
$route = Route::getRoute('entry.add');

2 个答案:

答案 0 :(得分:4)

首先,这是你如何通过它的名字获得一个路由对象:

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

路由对象的方法为getActionName(),所以:

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

答案 1 :(得分:1)

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

例如:

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

它将返回如下响应:

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