检查给定的 url 字符串将调用什么操作

Checking what action would be called by a given url string

在 Laravel (5.6) 中,我想查看给定的 url 字符串将调用什么路由。假设 url 是 "report/sales" 我想检查将调用哪个控制器的哪个函数,例如可以是 "ReportController@salesreport"。它与 action() 函数有点相反,但我找不到类似的东西。

如果有人有解决方案那就太好了。

您可以通过容器检索 Router 实例并检索所有路由,然后过滤检索到的路由以仅匹配 url 属性等于给定 url 字符串的路由。最后,为每个路由选择匹配的控制器动作。

$routes = app('router')->getRoutes()->getRoutes();
$target = 'report/sales';

$actions = collect($routes)->filter(function($route) use ($target) {
    return $route->uri == $target;
})->pluck('action.controller');

dd($actions);

如果您只需要获取一条路线(例如:没有相同URL但动词不同的路线),只需将filter替换为first即可停在第一条匹配发生。因此,您将不再需要 pluck,因为您将获得一个 Route 实例,而不是一个集合:

$routes = app('router')->getRoutes()->getRoutes();
$target = 'report/sales';

$action = collect($routes)->first(function($route) use ($target) {
    return $route->uri == $target;
})->action['controller'];

dd($action);

Laravel 不提供直接检查与 URI 匹配的路由的方法,可能是因为它 performs multiple assertions 在匹配期间用于主机、方法等。几乎所有匹配都使用 Request 对象进行比较。

使用现有功能的最快方法是手动创建一个 Request 对象,其中包含您希望匹配的详细信息(HTTP 方法、URI 等)。完成后,您可以拿起路由器并查看:

$request = \Illuminate\Http\Request::create('/report/sales');

$routes = Route::getRoutes(); // Or, you can get the Router directly, through app(), etc.

try {
    $route = $routes->match($request);

    $action = $route->getActionName();
} catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
    // No matching route was found.
} catch (\Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
    // The URI matches a route for a different HTTP method
}