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

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

Merged
merged 2 commits into from
Jul 19, 2022
Merged

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

merged 2 commits into from
Jul 19, 2022

Conversation

emargareten
Copy link
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
Copy link
Contributor

supun-io commented Sep 25, 2022

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.

None yet

3 participants