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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化