doulu4413 2015-07-28 16:10
浏览 87
已采纳

如何在URL中使用laravel路由来获取未知数量的参数?

For example, I'm publishing books with chapters, topics, articles:

http://domain.com/book/chapter/topic/article

I would have Laravel route with parameters:

Route::get('/{book}/{chapter}/{topic}/{article}', 'controller@func')

Is it possible, in Laravel, to have a single rule which caters for an unknown number of levels in the book structure (similar to this question)? This would mean where there are sub-articles, sub-sub-articles, etc..

  • 写回答

1条回答 默认 最新

  • dpwo36915 2015-07-28 16:16
    关注

    What you need are optional routing parameters:

    //in routes.php
    Route::get('/{book?}/{chapter?}/{topic?}/{article?}', 'controller@func');
    
    //in your controller
    public function func($book = null, $chapter = null, $topic = null, $article = null) {
      ...
    }
    

    See the docs for more info: http://laravel.com/docs/5.0/routing#route-parameters

    UPDATE:

    If you want to have unlimited number of parameters after articles, you can do the following:

    //in routes.php
    Route::get('/{book?}/{chapter?}/{topic?}/{article?}/{sublevels?}', 'controller@func')->where('sublevels', '.*');
    
    //in your controller
    public function func($book = null, $chapter = null, $topic = null, $article = null, $sublevels = null) {
      //this will give you the array of sublevels
      if (!empty($sublevels) $sublevels = explode('/', $sublevels);
      ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题