Laravel 4 how get routes by group name

做~自己de王妃 提交于 2019-12-11 08:32:24

问题


In Laravel, I know I can get all routes using `Route::getRoutes() but I can't find if it is possible to get a list of all routes contained in a specified group.

For example, i have this route file:

Route::group(array('group_name' => 'pages'), function() {
    Route::any('/authentication', array('as' => 'authentication', 'uses' => 'LogController@authForm' ));
    Route::group(array('before' => 'auth_administration'), function() {
        Route::any('/tags_category/index', array('as' => 'index-tags-categories', 'uses' => 'TagsCategoryController@index'));
        Route::any('/tags_category/update', array('as' => 'update-tags-category', 'uses' => 'TagsCategoryController@update'));
    });
});

Route::group(array('before' => 'auth_administration'), function() {
    Route::any('/tags_category/store', array('as' => 'store-tags-category', 'uses' => 'TagsCategoryController@store')); 
    Route::any('/tags_category/update/{id}', array('as' => 'update-form-tags-category', 'uses' => 'TagsCategoryController@updateForm')); 
    Route::any('/tags_category/delete/{id}', array('as' => 'delete-tags-category', 'uses' => 'TagsCategoryController@delete'));
}); // operazioni protette 

and in my controller i want obtain only routes contained in the first group (the one with the variable 'group_name').

Is it possible? If yes how I can do it? Thanks


回答1:


The attributes passed to the group in the first parameter are stored on the route in the action array. This array can be accessed via the getAction() method on the route. So, once you get access to the route objects, you can filter based on this information.

$name = 'pages';
$routeCollection = Route::getRoutes(); // RouteCollection object
$routes = $routeCollection->getRoutes(); // array of route objects
$grouped_routes = array_filter($routes, function($route) use ($name) {
    $action = $route->getAction();
    if (isset($action['group_name'])) {
        // for the first level groups, $action['group_name'] will be a string
        // for nested groups, $action['group_name'] will be an array
        if (is_array($action['group_name'])) {
            return in_array($name, $action['group_name']);
        } else {
            return $action['group_name'] == $name;
        }
    }
    return false;
});

// array containing the route objects in the 'pages' group
dd($grouped_routes);



回答2:


User artisan to list all routes for the application

php artisan routes --name=admin

in Laravel 5

php artisan route:list --name=admin


来源:https://stackoverflow.com/questions/29941071/laravel-4-how-get-routes-by-group-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!