5

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', '.*');
3
  • stackoverflow.com/questions/13297278/… might answer your question. Commented Jan 6, 2016 at 14:05
  • (:any) doesn't seem to work in Laravel 5 anymore ? {any} and {all} do work, but don't match the sub-paths it seems...
    – Dylan
    Commented Jan 6, 2016 at 14:22
  • There is nothing special about {any} and {all}, as these are just normal route parameters. Commented Jan 6, 2016 at 15:23

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.