问题是显而易见的。
我们知道,使用Route::getRoutes()
方法可以像这样获取Laravel项目中所有定义的路由:
$routeCollection = Route::getRoutes();
$arr = [];
foreach ($routeCollection as $value) {
$arr[] = $value->getPath();
}
return array_unique($arr);
但是我想在特定路径中获取所有定义的路由,例如/admin
.
我认为可以将路径名传递给getRoutes()
这样做,但对我不起作用。
我该怎么做?
这是一个利用 Laravel 集合的解决方案:
$routes = collect(Route::getRoutes()->getRoutes())->reduce(function ($carry = [], $route) {
!starts_with($route->getPath(), 'admin') ?: $carry[] = $route->getPath();
return $carry;
});
所以现在 routes
数组将返回以 admin
开头的路由路径列表。这是那里发生的事情:
使用
Route::getRoutes()
将返回一个RoutesCollection
,该具有自己的getRoutes
方法,该方法返回Illuminate'Routing'Route
实例的平面数组。然后,您可以将其传递给collect
方法,该方法将返回所有这些路由的Collection
。现在,您只需要删除不以
admin
开头的值。如果这是一个可以使用filter
方法轻松实现的简单值数组,但由于这是一个对象数组,并且您希望只能通过方法调用访问的path
字符串getPath
,则可以将集合的reduce
方法用作解决方法。
此外,您会注意到该条件会检查路径是否以 admin
开头而不是以 /admin
开头。这是因为 Laravel 路由器将在构建路由集合时自动去除前导斜杠。
您可以在 Laravel 文档中阅读有关集合的更多信息。
我会选择正则表达式:
$routeCollection = Route::getRoutes();
$arr = [];
foreach ($routeCollection as $value) {
if (preg_match('/^'/?admin/', $value->getPath())) {
$arr[] = $value->getPath();
}
}
$filteredRoutes = array_unique($arr);
您可以使用此应用程序:
$routeCollection = Route::getRoutes();
$adminRoutes = [];
foreach ($routeCollection as $value) {
strpos($value->getPath(), 'admin') === false ?: $adminRoutes[] = $value->getPath();
}