From 23912e779356715a1719eb3720bd7b9327c5e463 Mon Sep 17 00:00:00 2001 From: Propaganistas Date: Mon, 15 Nov 2021 21:14:14 +0100 Subject: [PATCH] [8.x] Enum casts accept backed values (#39608) * Enum casts accept backed values * styleci --- .../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 da5538f54dcd..2ac2a8e7dfa2 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -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; + } } /** diff --git a/tests/Integration/Database/EloquentModelEnumCastingTest.php b/tests/Integration/Database/EloquentModelEnumCastingTest.php index 51bf7bd6cc1a..57043ca5bf43 100644 --- a/tests/Integration/Database/EloquentModelEnumCastingTest.php +++ b/tests/Integration/Database/EloquentModelEnumCastingTest.php @@ -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([