laravel 如何使用相同的控制器方法对多个路由进行分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38886622/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:17:50  来源:igfitidea点击:

How to group multiple routes with the same controller method?

laravellaravel-5.2

提问by Alex

I have the following in my routes.php:

我有以下内容routes.php

Route::get('test/foo', 'TestController@index');

Route::get('test/bar', 'TestController@index');

Route::get('test/baz', 'TestController@index');

and I am trying to reduce this to the following:

我试图将其减少到以下几点:

Route::get(either 'test/foo' or 'test/bar' or 'test/baz', 'TestController@index');

One documented approachthat would sort of apply here, is to place a regex constraint to the route:

一种适用于此处的记录方法是对路线放置正则表达式约束:

Route::get('test/{uri}','TestController@index')->where('uri', 'regex for foo, bar, and baz...');

However, this solution would be ugly. Isn't there an elegant way to just express

然而,这个解决方案会很丑陋。难道没有一种优雅的方式来表达

{uri} in foo,bar,baz

in Laravel's language? Otherwise, what would the regex look like?

用 Laravel 的语言?否则,正则表达式会是什么样子?

Thanks!

谢谢!

P.S.I've read this, but it didn't apply to my case with 3 routes.

PS我读过这个,但它不适用于我的 3 条路线的情况。

回答by haitran

I'm not sure why you said that RegExr is ugly. I basically think it is one of the most powerful tool.

我不知道你为什么说 RegExr 很丑。我基本上认为它是最强大的工具之一。

For your case, I think the below snippet should do the job:

对于您的情况,我认为以下代码段应该可以完成这项工作:

Route::get('user/{name}', function ($name) { // }) ->where('name', '(foo|bar|baz)');

Route::get('user/{name}', function ($name) { // }) ->where('name', '(foo|bar|baz)');

The (foo|bar|baz)RegExr will match any of these string: 'foo', 'bar', 'baz'. So, if you need more, just add the vertical bar and add the needed string.

(foo|bar|baz)RegExr将匹配任何这些字符串:“富”,“酒吧”,“巴兹”。因此,如果您需要更多,只需添加垂直条并添加所需的字符串。