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.