Skip to content

fix Enums not being cast when calling Model::toArray() #2522

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

Merged
merged 1 commit into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
}

if ($this->isEnumCastable($key) && (! $castValue instanceof Arrayable)) {
$castValue = $castValue !== null ? $this->getStorableEnumValue($attributes[$key]) : null;
$castValue = $castValue !== null ? $this->getStorableEnumValue($castValue) : null;
}

if ($castValue instanceof Arrayable) {
Expand Down
15 changes: 15 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -786,4 +786,19 @@ public function testFirstOrCreate(): void
$check = User::where('name', $name)->first();
$this->assertEquals($user->_id, $check->_id);
}

public function testEnumCast(): void
{
$name = 'John Member';

$user = new User();
$user->name = $name;
$user->member_status = MemberStatus::Member;
$user->save();

/** @var User $check */
$check = User::where('name', $name)->first();
$this->assertSame(MemberStatus::Member->value, $check->getRawOriginal('member_status'));
$this->assertSame(MemberStatus::Member, $check->member_status);
}
}
6 changes: 6 additions & 0 deletions tests/models/MemberStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

enum MemberStatus: string
{
case Member = 'MEMBER';
}
2 changes: 2 additions & 0 deletions tests/models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
* @property string $username
* @property MemberStatus member_status
*/
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract
{
Expand All @@ -36,6 +37,7 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword
protected $casts = [
'birthday' => 'datetime',
'entry.date' => 'datetime',
'member_status' => MemberStatus::class,
];
protected static $unguarded = true;

Expand Down