Skip to content

[11.x] Add Request::enums method to retrieve an array of enums#53540

Merged
taylorotwell merged 3 commits into
laravel:11.xfrom
stevebauman:request-enums-method
Nov 18, 2024
Merged

[11.x] Add Request::enums method to retrieve an array of enums#53540
taylorotwell merged 3 commits into
laravel:11.xfrom
stevebauman:request-enums-method

Conversation

@stevebauman

@stevebauman stevebauman commented Nov 16, 2024

Copy link
Copy Markdown
Contributor

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
Copy Markdown

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
Copy Markdown

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

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