Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Fallback Routes in Laravel 9

How to use the fallback route in Laravel 9?

Do you want to use the fallback route in Laravel 9 Laravel application?

Use Fallback Routes in Laravel
Defining Fallback route

This step-by-step tutorial helps you learn how to use the fallback route in the Laravel application with the help of the fallback method.

The fallback route in Laravel

Route::fallback method, you may define a route that will be executed when no other route matches the incoming request, Typically, unhandled requests will automatically render a “404” page via your application’s exception handler.

Why you should use the fallback route in Laravel

If a user of our application tries to access a page that doesn’t exist like:- (404 Not Found).

First example:– The user wants to access a blog post from the database that does not exist, so if you want to show a static message or show a page where we list all the recent and related blog posts rather than the 404 page, we could return a function that the user stays on our web page, we think of second solution is best.

Second example:- E-commerce applications like Flipkart and amazon, you notice whenever you search for a non-related product on the application, it always shows something related or featured products, to stay on the application.

So, let’s implement the fallback functionality in laravel to show related queries rather than a 404 page.

Defining a Fallback controller

Create a controller

php artisan make:controller 

Defining Fallback route

Now, we implement a fallback route and we can add more functionality than a 404-page fallback route need to be defined inside the web.php file at the end of the route file.



use Illuminate\Support\Facades\Route;

#Fallback Route Example



namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FallbackController extends Controller
    public function __invoke()
        return view('fallback.index');

Recommended article:- Handle multiple pages using a single route using the __Invoke method In Laravel.

Create a folder and a blade file


<h1>Fallback page once a route doesn't exist.</h1>
<h2>Related Post | Featured Post</h2>

Note:- Now, you can pass your post or product model from the controller and shows the posts and products in the fallback blade file.

I hope that this article helped you learn an example of the Fallback Route in Laravel 9, with the help of the Laravel fallback method example. You may also want to check out our guide on How to set limits on login attempts in laravel 9 example in the Laravel application.