Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group multiple routes with the same controller method?

I have the following in my 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 approach that 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?

Thanks!

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

like image 692
Alex Avatar asked Aug 11 '16 03:08

Alex


People also ask

What is Route grouping?

Route groups allow you to share route attributes, such as middleware, across a large number of routes without needing to define those attributes on each individual route.


1 Answers

I'm not sure why do you say that RegEx is ugly. I basically think RegEx is one of the most powerful tools.

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

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 pipe (|) and add the needed string.

like image 114
haitran Avatar answered Sep 24 '22 16:09

haitran