Skip to content

Commit

Permalink
[8.x] Enum casts accept backed values (laravel#39608)
Browse files Browse the repository at this point in the history
* Enum casts accept backed values

* styleci
  • Loading branch information
Propaganistas authored Nov 15, 2021
1 parent da7aa38 commit 23912e7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,15 @@ function () {
*/
protected function setEnumCastableAttribute($key, $value)
{
$this->attributes[$key] = isset($value) ? $value->value : null;
$enumClass = $this->getCasts()[$key];

if (! isset($value)) {
$this->attributes[$key] = null;
} elseif ($value instanceof $enumClass) {
$this->attributes[$key] = $value->value;
} else {
$this->attributes[$key] = $enumClass::from($value)->value;
}
}

/**
Expand Down
15 changes: 15 additions & 0 deletions tests/Integration/Database/EloquentModelEnumCastingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,21 @@ public function testEnumsAcceptNullOnSave()
], DB::table('enum_casts')->where('id', $model->id)->first());
}

public function testEnumsAcceptBackedValueOnSave()
{
$model = new EloquentModelEnumCastingTestModel([
'string_status' => 'pending',
'integer_status' => 1,
]);

$model->save();

$model = EloquentModelEnumCastingTestModel::first();

$this->assertEquals(StringStatus::pending, $model->string_status);
$this->assertEquals(IntegerStatus::pending, $model->integer_status);
}

public function testFirstOrNew()
{
DB::table('enum_casts')->insert([
Expand Down

0 comments on commit 23912e7

Please sign in to comment.