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

血红的双手。 提交于 2020-01-11 02:32:48

问题


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:


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


来源:https://stackoverflow.com/questions/31681750/how-to-use-laravel-routing-for-unknown-number-of-parameters-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!