How to handle access to undefined routes in Laravel 11 using fallback() method
How to use fallback() method in Laravel 11 application to return custom page or response for undefined routes
Introduction
In this article i’ll demonstrate how to handle access to undefined routes in Laravel 11 using the fallback()
method.
What is Fallback() Method
In Laravel 11, the fallback()
method is used to define a custom route with response (web page or json) when the incoming request (via browser or API) does not match any defined / existing routes in the application.
By default in Laravel, the 404
page via the application’s exception handler is rendered when there’s an unhandled request.
If the fallback route is defined in the routes/web.php
file all the middleware in the web middleware group will apply to the route including any custom middleware you choose to add.
The fallback()
method is defined once in any route file (api.php or web.php or any custom route file)
Fallback() method Syntax
The fallback()
method of the Route facade takes in a callback function:
Route::fallback(function () {
// ... fallback route response (web page or json response)
});
Example of Fallback() method for web routes
use Illuminate\Support\Facades\Route;
Route::fallback(function () {
return response()->view('errors.404', [], 404);
});
Trying to access http://127.0.0.1:8000/blog or any route that is not defined will return the custom page defined as the fallback route. This could be any kind of view depending on the functionality of the application
Example of Fallback() method for API routes
Trying to access http://127.0.0.1:8000/api/v1/blog or any API route that is not defined will return the custom json
response defined in the fallback() method.
Route::fallback(function () {
return response()->json([
'message' => 'Route not found. Kindly check the URL and try again.'
], 404);
});
- Output
Conclusion
In this article we’ve learn in-depth about the fallback()
method in Laravel 11 that is used to return custom page or json response when there are no define routes / URLs for the request coming into the application.
Find this article useful… kindly share with your network and feel free to use the comment section for questions, answers, and contributions.