Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Override default 404 behavior in Laravel

When working with Laravel routes, if it’s not able to find the matching route, a typical 404 HTTP response will be generated and returned back.

Take the following for example.

Route::get('/user/{user}', function (User $user) {
    return $user->email;
});

As you can tell, here for this route, if a user for the matching ID exists, it will return the intended response based on the route model binding.

But in case, if it’s not able to find the specified user, it will return a typical 404 response.

How do you override this behavior? Enter the Route::fallback method

The Route::fallback method

Laravel ships with this Route::fallback method that you can use to define a route that will be executed when no other route matches the incoming request.

So, for instance, in our previous example, if there’s no matching route for a specified user, the application should move the user to the dashboard.

You can accomplish this behavior using the Route::fallback method like so.

Route::fallback(function () {
    return view('dashboard');
});

You can put this fallback route to the routes/web.php along with the other routes (preferably at the end of the file).

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?