简体   繁体   English

Laravel路由带有可选的子路径

[英]Laravel routes with an optional sub-path

I'm trying to create a Route in routes.php that can handle optional unlimited sub-paths. 我试图在routes.php中创建一个可以处理可选的无限子路径的Route。

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). (当然, echo $url仅用于测试)。

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. 我现在使用一个技巧来避免这种情况,通过在子路径中使用~代替/ ,然后再替换它们,但是我想知道是否有更好的方法,因此可以在URL中使用/

UPDATE 更新

Found the solution, thanks to Mark : 找到了解决方案,这要归功于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. 您必须在一定程度上为您的url定义路由。 I suppose the number of sub-routes are/have to be predefined, say you'd want to go with 4 url parts. 我猜想子路由的数量是/必须预先定义的,比如说您想使用4网址部分。

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). 似乎@Mark Davidson在SO答案中建议的不再支持(:any)参数(我无法在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. 但是,采用第二种方法的唯一缺点是,您可能不知道应该嵌套到什么程度以提取url子部分。

With the former approach though, you know the extent . 但是,使用前一种方法,您可以知道范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM