laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.64k stars 11.04k forks source link

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

Closed stevebauman closed 3 days ago

stevebauman commented 5 days ago

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 ❤️

Ali-Hassan-Ali commented 5 days ago

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 commented 4 days ago

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