【问题标题】:How to use laravel routing for unknown number of parameters in URL?如何对 URL 中未知数量的参数使用 laravel 路由?
【发布时间】:2015-10-19 07:55:33
【问题描述】:

例如,我正在出版带有章节、主题、文章的书籍:

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

我会有带参数的 Laravel 路由:

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

在 Laravel 中是否有可能有一个规则来满足书籍结构中未知数量的级别(类似于 this question)?这意味着哪里有子文章,子子文章等。

【问题讨论】:

    标签: php laravel laravel-routing


    【解决方案1】:

    你需要的是可选的路由参数:

    //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) {
      ...
    }
    

    有关更多信息,请参阅文档:http://laravel.com/docs/5.0/routing#route-parameters

    更新:

    如果想要文章后面的参数数量不限,可以这样做:

    //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);
      ...
    }
    

    【讨论】:

    • 澄清问题。我的意思是在{articles} 之后有无限数量的级别。 IE。 /sub-article/sub-sub-article/等等等等
    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2020-02-05
    • 2021-01-09
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多