Ad

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 :

/path/part1
/path/part1/part2
/path/part1/part2/part3
etc.

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.

UPDATE

Found the solution, thanks to Mark :

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

Answer

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:

Route::get('path/{url1?}/{url2?}/{url3?}/{url4?}', 
     function($url1 = null, $url2 = null, $url3 = null, $url4 = null){

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

Note:

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.

Ad
source: stackoverflow.com
Ad