Skip to content

[9.x] Adds enum casting to Request#43239

Merged
taylorotwell merged 2 commits into
laravel:9.xfrom
emargareten:9.x
Jul 19, 2022
Merged

[9.x] Adds enum casting to Request#43239
taylorotwell merged 2 commits into
laravel:9.xfrom
emargareten:9.x

Conversation

@emargareten

Copy link
Copy Markdown
Contributor

(same as #43169 for 9.x)

This PR allows to conveniently retrieve an input from the Request as an enum.

// Before
public function post(Request $request)
{
    $status = StatusEnum::tryFrom($request->input('status'));

    // do stuff with status enum...
}

// After
public function post(Request $request)
{
    $status = $request->enum('status', StatusEnum::class);

    // do stuff with status enum...
}

@taylorotwell taylorotwell merged commit bdf38d9 into laravel:9.x Jul 19, 2022
@supun-io

supun-io commented Sep 25, 2022

Copy link
Copy Markdown
Contributor

I just added a PR to improve type definitions of this.

By the way, I was thinking, shouldn't there be a way to get non-nullable Enum?

For example, if I validate the input as an enum, I know it is a valid Enum value later.

$request->validate(['type' => ['required', new Enum(MyEnum::class)]);

$type = $request->enum('type', MyEnum::class);
// currently this is MyEnum | null

Currently, $type can be null because tryFrom is used. But, as we have validated earlier, we may just need the exact enum. It is annoying to deal with null.

I had two ideas.

  1. Add a third-parameter to the enum method.
public function enum($key, $enumClass, $nullable = true) {}

Then, call it as $request->enum($key, $enumClass, false). But, this is not very fluent.

  1. Add a different method

As this is already deployed to public 9.0, we will need to reserve the enum name for nullable method. I am not sure about a name for the other method. enumNotNullable is too long.

Any ideas? @emargareten

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