Skip to main content
Tutorial Free

Route Fallback: If No Other Route is Matched

February 12, 2019
1 min read

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 yourdomain.com/abcde12345, 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' => [
        \App\Http\Middleware\EncryptCookies::class,
 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.