Laravel 10 How to Implement Fallback Route

Hello Artisan, today I'll show you how to use fallback route in our Laravel application. A fallback route in Laravel allows you to define a route that will be executed when no other route matches the incoming request. This can be useful for handling 404 errors or creating custom error pages. Let's see how to define a fallback route in Laravel.

Table of Contents

  1. Install Laravel App
  2. Create Controller
  3. Create Fallback Route
  4. Create Blade File
  5. Run Laravel App
  6. Output

Install Laravel App

Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command

composer create-project laravel/laravel Fallback

Feel free to ignore this step if you've already created the Laravel app.

Create Controller

In this step, we will create a new FallbackController with a __invoke method that calls a view file. Let's proceed with updating the code in the Controller file


namespace App\Http\Controllers;

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

Create Fallback Route

Moreover, you open the routes/web.php file and incorporate a fallback route using the controller name, similar to the example provided.


use App\Http\Controllers\Fallbackcontroller;
use Illuminate\Support\Facades\Route;

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!


Create Blade File

Here, we will create index.blade.php file with html code. so let's update as like the below

<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container">
    <h1>Call Fallback Route Once a Route Doesn't Exist.</h1>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>


Run Laravel App

After completing all the necessary steps, simply type the command provided below and hit enter to run the Laravel app.

php artisan serve

Now, Go to your web browser, type the given URL and view the app output


That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚