doulu4413 2015-07-28 08: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 08: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);
      ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部