dongpeiwei8589 2016-01-06 13:50
浏览 46
已采纳

Laravel路由带有可选的子路径

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', '.*');
  • 写回答

1条回答 默认 最新

  • duanbei1598 2016-01-06 15:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用