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.
Nice!
This is cool, thanks!
Cool!
I didn’t use this trick in laravel but used in symfony
New to Laravel and I like this idea. Was just thinking could make a migration.
url_typos_and_misfires
Could store
Url – url string
Count – if match url increment
Directed – the link directed from
This way you can see if you would like to add a new route or help find your own typos.
The problem with this is that it’ll match ANYTHING, so you can’t have for instance, your authentication routes anymore, they won’t work because they’ll get caught by this hack and you’ll be redirected.
what if we do not want add urls contains /admin ? how will we customize this?
Then create specific routes for /admin rules, above those bottom rules for everything else
Ok thanks for your reply.. I already have added the condition on URL. if URL contains /admin do not run this block 😛
and Thanks for this cool hack.. it saved alot of time
Cool info; thanks for sharing!
Works like Magic, thanks