2

Question is Obvious.

we know that with Route::getRoutes() method can get all defined routes in laravel project like this :

$routeCollection = Route::getRoutes();
$arr    =   [];

foreach ($routeCollection as $value) {
    $arr[] =    $value->getPath();
}

return array_unique($arr);

But I want to get all defined routes in specific path for example /admin.

I thought that can pass a path name to getRoutes() for do that but does not work for me.

How can I do that ?

Ahmad Badpey
  • 6,348
  • 16
  • 93
  • 159

3 Answers3

4

Here's a solution that makes use of Laravel's collections:

$routes = collect(Route::getRoutes()->getRoutes())->reduce(function ($carry = [], $route) {
    !starts_with($route->getPath(), 'admin') ?: $carry[] = $route->getPath();

    return  $carry;
});

So now the routes array will return a list of the route paths that start with admin. Here's what's going on there:

  • Using Route::getRoutes() will return a RoutesCollection which has its own getRoutes method that returns a flat array of Illuminate\Routing\Route instances. You can then pass that to the collect method which will return a Collection of all those routes.

  • Now you just have to remove the values that do not start with admin. If that was a simple array of values that could be easily achieved with the filter method, but since this is an array of objects and you want the path string that is accessible only via a method call to getPath, the collection's reduce method can be used instead as a workaround.

Also, you'll notice that the condition checks if the path starts with admin and not /admin. That's because the Laravel router will strip leading slashes automatically when building the route collection.


You can read more about collections in the Laravel Documentation.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
1

You can use this apporach:

$routeCollection = Route::getRoutes();
$adminRoutes = [];

foreach ($routeCollection as $value) {
    strpos($value->getPath(), 'admin') === false ?: $adminRoutes[] = $value->getPath();
}
Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • 1
    The `getRoutes()` method returns a `RoutesCollection` instance, and unlike a regular `Collection` it does not have any `where` method, so this won't work. Please revise your answer. – Bogdan Apr 06 '16 at 10:55
  • Now I will know that, thanks. I guess in this case best approach will be just to use simple loop to filter routes. I've updated my answer. – Alexey Mezenin Apr 06 '16 at 11:06
1

I would go for regex:

    $routeCollection = Route::getRoutes();
    $arr             = [];

    foreach ($routeCollection as $value) {
        if (preg_match('/^\/?admin/', $value->getPath())) {
            $arr[] = $value->getPath();
        }
    }
    $filteredRoutes = array_unique($arr);
Giedrius Kiršys
  • 5,154
  • 2
  • 20
  • 28