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

Adding support for non-backed enums #43728

Merged
merged 2 commits into from
Aug 16, 2022
Merged

Adding support for non-backed enums #43728

merged 2 commits into from
Aug 16, 2022

Conversation

ollieread
Copy link
Contributor

This PR adds support for non-backed enums when casting eloquent attributes. It works based on the fact that enum cases are glorified constants, so the constant() method will work for retrieving.

It also updates the $value param type for Illuminate\Database\Eloquent\Concerns\HasAttributes::setEnumCastableAttribute from \BackedEnum to \UnitEnum|string|int. It's worth noting that the original version should have technically been \BackedEnum|string|int because there are code paths for handling when it isn't an instance.

@taylorotwell taylorotwell merged commit f01d8b9 into laravel:9.x Aug 16, 2022
@ollieread ollieread deleted the non-backed-enum-support branch August 16, 2022 19:41
@foremtehan
Copy link
Contributor

foremtehan commented Aug 17, 2022

please add tests if possible, what happen if someone modify your code later

@johanmolen
Copy link

Should the non-backed enums also be implemented in the addCastAttributesToArray method?

@ollieread
Copy link
Contributor Author

Should the non-backed enums also be implemented in the addCastAttributesToArray method?

This is a very good point!

@ollieread
Copy link
Contributor Author

@laravel there's a valid point raised by @johanmolen, will fix this ASAP

@johanmolen
Copy link

@ollieread awesome, if you need help let me know.

@johanmolen
Copy link

@ollieread my quick fix for now (line 310):

if ($this->isEnumCastable($key) && (! ($attributes[$key] ?? null) instanceof Arrayable)) {
    if (! isset($attributes[$key])) {
        $attributes[$key] = null;
    } else if ($attributes[$key] instanceof BackedEnum) {
        $attributes[$key] = $attributes[$key]->value;
    } else {
        $attributes[$key] = $attributes[$key]->name;
    }
}

@ollieread
Copy link
Contributor Author

Added a fix in #43842 @johanmolen

@johanmolen
Copy link

@ollieread Awesome 💯

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