Search code examples
phplaravellaravel-routing

Check if route exists when Route::fallback present


I am attempting to determine if a given route exists while inside of Laravel's Route::fallback. The following snippet should throw a NotFoundHttpException exception, however I suspect that it is not due to the presence of the fallback (ie, the route does exist as a fallback).

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

For some context: I'd like to be able to hit a route that does exist and then display the contents of another route. This second route may end up not actually existing and I'd like to be able to catch that.

TIA


Solution

  • The result of Route::getRoutes()->match($next); will be an Illuminate\Routing\Route object. You can check this object for the value of the isFallback property.

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