Last month, I shared a description of how duplicate routes are resolved. Today I want to continue that discussion to talk about a unique kind of route: the fallback route.
As the name implies, a fallback route is used when no other route matches the incoming request.
But if you peek under the hood, you see Laravel sets a special fallback
flag on this route.
Then when routes are resolved, it treats the fallback specially, skipping over it until all other routes have been checked.
One common use case for the fallback route is to override the typical framework handling with the 404
error page.
If all you need is to customize the error page, Laravel gives you a way to do that with a Blade view.
But if you want some extra logic in the 404
flow, this fallback route gives you the hook to do that.
Maybe you want to do some special logging for 404s or show a different page based on the logged-in user, or any other special logic you can dream up.
With the fallback route, you can add on middleware, route to a controller action, or do anything else you can do in a normal route definition.
It's important to note that with fallback routes, the order is still important. Even though Laravel tracks that flag and segments it from other routes, in my experience, a fallback route should always be the last route defined in your routes file.
Here to help,
Joel
P.S. We're slowly coming up on the end of the quarter. Don't forget you can grab the newest volume of tips or catch up on ones you missed.