Laravel doesn’t have a way to use wildcards in routes by default. However, you can add one in by using route parameters and regex constraints. Don’t worry: it’s super-easy to set up!
Start by picking a term to use as the wildcard (for these examples, I chose “whatever”). Insert that term as a route parameter wherever you need a wildcard. At the end of your route, chain on the where
method to tell Laravel you want to parse a route parameter with a regex. The first argument is the term you’ve chosen; the second argument is .+
, which will select everything in the route parameter.
Route::get('some/route/{whatever}', function(){
// do your stuff here
})->where('whatever', '.+');
Voila! You’ve just created a route wildcard!
There are a variety of uses for this. One is if you have a bunch of old links which start with the same prefix, but don’t end in an identifiable pattern. Another is if, instead of returning a 404 error for non-existing routes, you want to take some other action (like a redirect back to the home page).
You aren’t limited to just catching whatever’s on the end of your url, either. You can stick the wildcard in the middle of the url and it will catch everything in between!
// Catch anything starting with /some/route and ending with /after
Route::get('some/route/{whatever}/after', function(){
// do your stuff here
})->where('whatever', '.+');
There are a couple of catches you should be aware of. One is that you can’t use a wildcard and another route parameter right next to each other in the same slash block.
// This won't work.
Route::get('some/route/{param}{whatever}', function(){
// do your stuff here
})->where('whatever', '.+');
Laravel will pick up on {param}
and add everything in {whatever}
as part of it. To get around this, if you are able, you can add a delimiting character in between the two.
// This works.
Route::get('some/route/{param}.{whatever}', function(){
// do your stuff here
})->where('whatever', '.+');
Another catch happens when your wildcard parameter doesn’t always show up in the url. For instance, if you want to redirect /some/route
and /some/route/
, using /some/route{whatever}
won’t work because Laravel is expecting something to follow /some/route
(the slash is ignored). To compensate, just make the wildcard parameter optional by using a question mark.
// Use a question mark when the wildcard won't always show up in the route.
Route::get('some/route{whatever?}', function(){
// do your stuff here
})->where('whatever', '.+');
Hope this makes your life a little bit easier!