Route Fallback: If No Other Route is Matched

Laravel 5.5.5 introduced a new feature in routing, called Route::fallback(). Basically, if no route is matched, then fallback function is a way to override default 404 page and introduce additional logic. Here’s how it works.

In your routes/web.php file, at the very end, after all the routes, you can specify something like this:

Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('/home', 'HomeController@index');
    Route::resource('tasks', 'Admin\TasksController');

// Some more routes....

Route::fallback(function() {
    return 'Hm, why did you land here somehow?';

And if someone enters random URL like, here’s what will show up:

Note, that this Route::fallback() method should go at the very end of routes file, after everything.

Another side effect of this: instead of just default 404 page, this Route::fallback() will follow all the Middlewares in ‘web’ group, from app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // \Illuminate\Session\Middleware\AuthenticateSession::class,        \Illuminate\View\Middleware\ShareErrorsFromSession::class,

Like our articles?
Check out our Laravel online courses!


  1. Hi Povilas,
    Thank you for the article and I’m using route fallback at the moment in my web.php
    There’s 1 problem:
    because the Route::fallback(function() is a closure I cannot use php artisan route:cache anymore.
    Have you found a way around this one?

    • Hi Niels, route:cache doesn’t work with closure routes, there’s no workaround for this, unfortunately, at least nothing I know of.

    • Niels/ Povilas

      I had the same. Do this:
      and then create a App\Http\Controllers\ControllerFallback class (in the logical directory) with [magic] public function __invoke() that returns response(‘whatever’, 200) [Or returns redirect(…) if you prefer]

      Confusingly, you MUST NOT add
      use App\Http\Controllers\ControllerFallback;
      at the top of routes/web.php … otherwise Laravel hunts for App\Http\Controllers\App\Http\Controllers\ControllerFallback



Please enter your comment!
Please enter your name here