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 Request::enums method to retrieve an array of enums #53540

Merged
merged 3 commits into from
Nov 18, 2024

Conversation

stevebauman
Copy link
Contributor

@stevebauman stevebauman commented Nov 16, 2024

Description

Right now it's possible to retrieve a single enum from a request via the enum method, but not an array of them easily.

This PR adds an enums method to retrieve a potential array of enums provided in a request.

Usage

Consider a "webhooks" controller where a user can create a webhook for a given URL and array of events:

// app/Http/Controllers/WebhookController.php

public function store(Request $request)
{
    $request->validate([
        'url' => 'required|url',
        'events' => 'required|array',
        'events.*' => Rule::enum(WebhookEvent::class),
    ]);

    // [WebhookEvent::UserCreated, WebhookEvent::UserUpdated]
    $events = $request->enums('events', WebhookEvent::class);
}

This works nicely in tandem with Laravel's built-in AsEnumArrayObject cast for Eloquent:

https://laravel.com/docs/11.x/eloquent-mutators#casting-arrays-of-enums

Webhook::create([
    'events' => $request->enums('events', WebhookEvent::class),
    // ...
]);

Let me know your thoughts! Thanks so much for your time ❤️

@stevebauman stevebauman changed the title [11.x] Add Request::enums method to retrieve an array of enums from a request [11.x] Add Request::enums method to retrieve an array of enums Nov 16, 2024
@Ali-Hassan-Ali
Copy link

A fantastic idea that greatly simplifies working with enums! Such an addition enhances usability and aligns perfectly with Laravel's philosophy of making common tasks easier. 👏

@zakariaarrid
Copy link

Hi @stevebauman , just a thought—maybe you could move isBackedEnum to a helper?

@taylorotwell taylorotwell merged commit de6c755 into laravel:11.x Nov 18, 2024
31 checks passed
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.

4 participants