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.
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.
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
<?php
namespace App\Http\Controllers;
class Fallbackcontroller extends Controller
{
public function __invoke()
{
return view('fallback.index');
}
}
Moreover, you open the routes/web.php file and incorporate a fallback route using the controller name, similar to the example provided.
<?php
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!
|
*/
Route::fallback(FallbackController::class);
Here, we will create index.blade.php file with html code. so let's update as like the below
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<title></title>
</head>
<body>
<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>
</div>
</body>
</html>
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
http://127.0.0.1:8000
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. ๐