diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index 85049922dcb1..f9d1ba0d3b5e 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -2463,7 +2463,12 @@ public function offsetSet($offset, $value): void */ public function offsetUnset($offset): void { - unset($this->attributes[$offset], $this->relations[$offset], $this->attributeCastCache[$offset]); + unset( + $this->attributes[$offset], + $this->relations[$offset], + $this->attributeCastCache[$offset], + $this->classCastCache[$offset] + ); } /** diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index fb24946d429c..a085d3ea31e4 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -53,6 +53,8 @@ use Illuminate\Support\InteractsWithTime; use Illuminate\Support\Stringable; use Illuminate\Support\Uri; +use Illuminate\Tests\Database\stubs\TestCast; +use Illuminate\Tests\Database\stubs\TestValueObject; use InvalidArgumentException; use LogicException; use Mockery as m; @@ -2823,6 +2825,17 @@ public function testMergeCastsMergesCastsUsingArrays() $this->assertEquals($model->getCasts()['bar'], 'MyClass:myArgumentA,myArgumentB'); } + public function testUnsetCastAttributes() + { + $model = new EloquentModelCastingStub; + $model->asToObjectCast = TestValueObject::make([ + 'myPropertyA' => 'A', + 'myPropertyB' => 'B', + ]); + unset($model->asToObjectCast); + $this->assertArrayNotHasKey('asToObjectCast', $model->getAttributes()); + } + public function testUpdatingNonExistentModelFails() { $model = new EloquentModelStub; @@ -3837,6 +3850,7 @@ protected function casts(): array 'asCustomEnumArrayObjectAttribute' => AsEnumArrayObject::of(StringStatus::class), 'singleElementInArrayAttribute' => [AsCollection::class], 'duplicatedAttribute' => 'int', + 'asToObjectCast' => TestCast::class, ]; } diff --git a/tests/Database/stubs/TestCast.php b/tests/Database/stubs/TestCast.php new file mode 100644 index 000000000000..4127bcd42598 --- /dev/null +++ b/tests/Database/stubs/TestCast.php @@ -0,0 +1,49 @@ + null, + ]; + } + + return [ + $key => json_encode($value->toArray()), + ]; + } +} diff --git a/tests/Database/stubs/TestValueObject.php b/tests/Database/stubs/TestValueObject.php new file mode 100644 index 000000000000..a9e67727e107 --- /dev/null +++ b/tests/Database/stubs/TestValueObject.php @@ -0,0 +1,34 @@ +myPropertyA = $test['myPropertyA']; + } + if (! empty($test['myPropertyB'])) { + $self->myPropertyB = $test['myPropertyB']; + } + + return $self; + } + + public function toArray(): array + { + if (isset($this->myPropertyA)) { + $result['myPropertyA'] = $this->myPropertyA; + } + if (isset($this->myPropertyB)) { + $result['myPropertyB'] = $this->myPropertyB; + } + + return $result ?? []; + } +}