Laravel Routes With An Optional Sub-path

- 1 answer

I'm trying to create a Route in routes.php that can handle optional unlimited sub-paths.

Route::get('/path/{url}', function($url){
  echo $url;

The url's can be the following :


But because of the / in the url's with a subpath they don't match, so nothing happens. (The echo $url is just for testing, of course).

I now use a trick to avoid this, by using ~ instead of / for the subpaths, and then replace them afterwards, but I would like to know if there's a better way so I can just use / in the URL's.


Found the solution, thanks to Mark :

Route::get('/path/{all}', function($url){
  echo $url;
})->where('all', '.*');


There has to be an extent for the url to which you'd want to define your routes for. I suppose the number of sub-routes are/have to be predefined, say you'd want to go with 4 url parts.

If that is the case, then using optional parameters would be the best choice:

     function($url1 = null, $url2 = null, $url3 = null, $url4 = null){

     //check if sub-routes are defined and combine them to produce the desired url


It seems that (:any) parameter is not supported anymore as suggested by @Mark Davidson in the SO answer (I couldn't reproduce it in laravel 5.0).

Meanwhile, you could also use regular expressions to achieve the desired effect, as in the following (might be quite similar to your own approach):

Route::get('/{url}', function ($url) {

// other url parts can be extracted from $url

})->where('url', '.*');

But the only disadvantage in going with the second approach is that you might not know to what extent should you go nested to extract the url sub-parts.

With the former approach though, you know the extent.