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

gre*_*ner 6 php laravel laravel-routing

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

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

我会使用参数的Laravel路线:

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

在Laravel中,是否有可能只有一个规则可以满足图书结构中未知数量的级别(类似于这个问题)?这意味着哪里有子文章,子分文章等.

jed*_*ylo 10

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

//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) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文档: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);
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • - > where('sublevels','.*'); 是正确的答案,干得好 (2认同)