routes: redirect “everything else” to homepage

3348 0 0 0

Last Updated : 2024-06-25 17:19:24

how to redirect “everything else” to homepage in routes file

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:

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.

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.