Skip to content

Adding support for non-backed enums#43728

Merged
taylorotwell merged 2 commits into
laravel:9.xfrom
ollieread:non-backed-enum-support
Aug 16, 2022
Merged

Adding support for non-backed enums#43728
taylorotwell merged 2 commits into
laravel:9.xfrom
ollieread:non-backed-enum-support

Conversation

@ollieread

Copy link
Copy Markdown
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

foremtehan commented Aug 17, 2022

Copy link
Copy Markdown
Contributor

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

@johanmolen

Copy link
Copy Markdown

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

@ollieread

Copy link
Copy Markdown
Contributor Author

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

This is a very good point!

@ollieread

Copy link
Copy Markdown
Contributor Author

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

@johanmolen

Copy link
Copy Markdown

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

@johanmolen

Copy link
Copy Markdown

@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
Copy Markdown
Contributor Author

Added a fix in #43842 @johanmolen

@johanmolen

Copy link
Copy Markdown

@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