Routes file: redirect "everything else" to homepage

We all know that file app/Http/routes.php is used for listing all possible routes we need for our application. But what if we need to define a rule for "everything else"? Like, we have a list of our routes, and if the URL doesn't match any of those rules - we want to, for example, redirect to homepage instead of showing 404 error. Actually, there's a really simple "hack" for that. Basically, at the very end of your routes.php file you need to place the rule with where condition. Like this:
Route::any('{query}',
  function() { return redirect('/'); })
  ->where('query', '.*');
This line at the end of Routes file means that and URL query string that doesn't match anything above that line - will redirect to homepage. Of course, you can change that function to throw any other kind of error, log something etc.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials