How to use laravel routing for unknown number of parameters in URL?

后端 未结 1 443
刺人心
刺人心 2021-01-05 10:27

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

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

I would have Laravel route with

相关标签:
1条回答
  • 2021-01-05 11:03

    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);
      ...
    }
    
    0 讨论(0)
提交回复
热议问题