当 Route::fallback 存在时检查路由是否存在

时间:2021-07-15 14:24:36

标签: php laravel laravel-routing

我正在尝试确定在 Laravel 的 Route::fallback 内是否存在给定的路由。下面的代码片段应该抛出一个 NotFoundHttpException 异常,但是我怀疑这不是由于存在后备(即,路由确实作为后备存在)。

Route::fallback(function () use ($routes) {
    try {
        $next = Request::create('does-not-exist');
        Route::getRoutes()->match($next);
    } catch (NotFoundHttpException) {
        // Should end up here
    }
});

对于某些上下文:我希望能够点击确实存在的路线,然后显示另一条路线的内容。这条第二条路线最终可能实际上并不存在,我希望能够抓住它。

TIA

1 个答案:

答案 0 :(得分:1)

Route::getRoutes()->match($next); 的结果将是一个 Illuminate\Routing\Route 对象。您可以检查此对象的 isFallback property 值。

Route::fallback(function () use ($routes) {
    $next = Request::create('does-not-exist');
    $route = Route::getRoutes()->match($next);
    if ($route->isFallback) {
        // do your thing
    }
});
相关问题