From 1f4590ab3cd637384b06ed71ed4ab734049815cb Mon Sep 17 00:00:00 2001 From: Propaganistas Date: Sun, 14 Nov 2021 18:11:11 +0100 Subject: [PATCH 1/2] Enum casts accept backed values --- .../Database/Eloquent/Concerns/HasAttributes.php | 10 +++++++++- .../Database/EloquentModelEnumCastingTest.php | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 46d9f2e7ac15..f0f20f1583b0 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -926,7 +926,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; + } else if ($value instanceof $enumClass) { + $this->attributes[$key] = $value->value; + } else { + $this->attributes[$key] = $enumClass::from($value)->value; + } } /** diff --git a/tests/Integration/Database/EloquentModelEnumCastingTest.php b/tests/Integration/Database/EloquentModelEnumCastingTest.php index c4e5de32ff5f..cbd3b378b90f 100644 --- a/tests/Integration/Database/EloquentModelEnumCastingTest.php +++ b/tests/Integration/Database/EloquentModelEnumCastingTest.php @@ -111,6 +111,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([ From 91222b16bc0f7212dd7c75dfa46fbbc5285b3536 Mon Sep 17 00:00:00 2001 From: Propaganistas Date: Sun, 14 Nov 2021 18:22:43 +0100 Subject: [PATCH 2/2] styleci --- src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index f0f20f1583b0..2cea09519f0d 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -930,7 +930,7 @@ protected function setEnumCastableAttribute($key, $value) if (! isset($value)) { $this->attributes[$key] = null; - } else if ($value instanceof $enumClass) { + } elseif ($value instanceof $enumClass) { $this->attributes[$key] = $value->value; } else { $this->attributes[$key] = $enumClass::from($value)->value;