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

[8.x] Enum casts accept backed values #39608

Merged
merged 2 commits into from
Nov 15, 2021
Merged

[8.x] Enum casts accept backed values #39608

merged 2 commits into from
Nov 15, 2021

Conversation

Propaganistas
Copy link
Contributor

@Propaganistas Propaganistas commented Nov 14, 2021

This PR builds upon #39315 to accept an enum's backed value as well.

Currently enum castable attributes first have to be instantiated (or be null) before they are accepted for casting:

enum MyEnum: string
{
    case Pending = 'pending';
}
$model = new Model;
$model->enum = MyEnum::Pending;

This can get verbose when handling requests:

// Request input = ['enum' => 'pending']

$request->merge([
   'enum' => MyEnum::from($request->input('enum')),
]);

$model->fill(
    $request->all()
);

By also accepting the backed values of an enum when casting, fluent model filling will be enabled (again).

$model = new Model;
$model->enum = 'pending';
// Request input = ['enum' => 'pending']

$model->fill(
    $request->all()
);

} else if ($value instanceof $enumClass) {
$this->attributes[$key] = $value->value;
} else {
$this->attributes[$key] = $enumClass::from($value)->value;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This forces values to be valid a enum case.

@themsaid
Copy link
Member

This looks ok to me. We do the same with date casting where we accept a date object or a string or an integer.

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