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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?