Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add whereEnum to route constraints #51104

Closed

Conversation

osbre
Copy link
Contributor

@osbre osbre commented Apr 17, 2024

Extending #46703 with tests and explanation, as suggested in the comment.

Introducing whereEnum lets us limit the scope of a route parameter by providing an enum class, rather than listing out all of its values in whereIn. I'll give an example:

Before whereEnum one would have to do:

Route::get('/posts/{type}')->whereIn('type', [PostType::TypeA->value, PostType::TypeB->value, PostType::TypeC->value]);
Route::get('/posts/{post}');

And now it's just:

Route::get('/posts/{type}')->whereEnum('type', PostType::class);
Route::get('/posts/{post}');

Note

Both of these routes have to co-exist under the same /posts/ path, thus the need for limiting/constraints.

Btw, do not confuse route constraining with the ability to inject an enum-type parameter in a controller.

@osbre
Copy link
Contributor Author

osbre commented Apr 18, 2024

Alternatively, I can make a different PR to make whereIn support enum values, so that it could be used like this:

Route::get('/posts/{type}')->whereIn('type', PostType::cases());

Let me know if this would be preferred instead of introducing whereEnum.

@joshmanders
Copy link
Contributor

Alternatively, I can make a different PR to make whereIn support enum values, so that it could be used like this:

Route::get('/posts/{type}')->whereIn('type', PostType::cases());

Let me know if this would be preferred instead of introducing whereEnum.

I like this route as it seems the cleanest.

@taylorotwell
Copy link
Member

https://laravel.com/docs/11.x/routing#implicit-enum-binding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants