Skip to content

Commit

Permalink
Reset Model::$unset when a model is saved or refreshed (#2709)
Browse files Browse the repository at this point in the history
* Override save() and refresh() functions to clear $this->unset
* Add tests reset Model::$unset when a model is saved or refreshed

---------

Co-authored-by: Richard Fila <“richardfila@capuk.org”>
Co-authored-by: Jérôme Tamarelle <jerome@tamarelle.net>
  • Loading branch information
3 people committed Jan 17, 2024
1 parent 3ffc759 commit da11d4d
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
3 changes: 2 additions & 1 deletion 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

Expand Down
26 changes: 26 additions & 0 deletions src/Eloquent/Model.php
Expand Up @@ -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;
}
}
15 changes: 15 additions & 0 deletions tests/ModelTest.php
Expand Up @@ -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));
Expand Down Expand Up @@ -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']);
Expand Down

0 comments on commit da11d4d

Please sign in to comment.