Laravel 5.1 通配符路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31569828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.1 Wildcard Route
提问by Jacob Haug
I'm creating a CMS that allows the user to define categories. Categories can either have additional categories under it or pages. How can I create a route in Laravel that will support a potentially unlimited number of URI segments?
我正在创建一个允许用户定义类别的 CMS。类别下可以有其他类别或页面。如何在 Laravel 中创建一个支持无限数量的 URI 段的路由?
I've tried the following....
我试过以下....
Route::get('/resources/{section}', ['as' => 'show', 'uses' => 'MasterController@show']);
I also tried making the route optional...
我还尝试将路线设为可选...
Route::get('/resources/{section?}', ['as' => 'show', 'uses' => 'MasterController@show']);
Keep in mind, section could be multiple sections or a page.
请记住,部分可以是多个部分或一个页面。
回答by jedrzej.kurylo
First, you need to provide a regular expression to be used to match parameter values. Laravel router treats /as parameter separator and you must change that behaviour. You can do it like that:
首先,您需要提供一个用于匹配参数值的正则表达式。Laravel 路由器将/视为参数分隔符,您必须更改该行为。你可以这样做:
Route::get('/resources/{section}',
[
'as' => 'show',
'uses' => 'MasterController@show'
])
->where(['section' => '.*']);
This way, whatever comes after /resources/and matches the regular expression will be passed to $sectionvariable in your controller.
这样,在/resources/ 之后并匹配正则表达式的任何内容都将传递给控制器中的$section变量。