diff --git a/CHANGELOG.md b/CHANGELOG.md index 27ab3d4d3..99b7bab08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,9 @@ # Changelog All notable changes to this project will be documented in this file. -## [4.0.3] - unreleased +## [4.0.3] - 2024-01-17 +- Reset `Model::$unset` when a model is saved or refreshed [#2709](https://github.com/mongodb/laravel-mongodb/pull/2709) by [@richardfila](https://github.com/richardfila) ## [4.0.2] - 2023-11-03 diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index 05a20bb31..a4797f16d 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -614,4 +614,30 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt return $attributes; } + + /** + * {@inheritDoc} + */ + public function save(array $options = []) + { + $saved = parent::save($options); + + // Clear list of unset fields + $this->unset = []; + + return $saved; + } + + /** + * {@inheritDoc} + */ + public function refresh() + { + parent::refresh(); + + // Clear list of unset fields + $this->unset = []; + + return $this; + } } diff --git a/tests/ModelTest.php b/tests/ModelTest.php index afa95c203..b979be1a8 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -496,8 +496,10 @@ public function testUnset(): void $user1->unset('note1'); $this->assertFalse(isset($user1->note1)); + $this->assertTrue($user1->isDirty()); $user1->save(); + $this->assertFalse($user1->isDirty()); $this->assertFalse(isset($user1->note1)); $this->assertTrue(isset($user1->note2)); @@ -526,6 +528,19 @@ public function testUnset(): void $this->assertFalse(isset($user2->note2)); } + public function testUnsetRefresh(): void + { + $user = User::create(['name' => 'John Doe', 'note' => 'ABC']); + $user->save(); + $user->unset('note'); + $this->assertTrue($user->isDirty()); + + $user->refresh(); + + $this->assertSame('ABC', $user->note); + $this->assertFalse($user->isDirty()); + } + public function testUnsetAndSet(): void { $user = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);