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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?