Skip to content

Commit da11d4d

Browse files
richardfilaRichard FilaGromNaN
authored
Reset Model::$unset when a model is saved or refreshed (#2709)
* 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>
1 parent 3ffc759 commit da11d4d

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

CHANGELOG.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# Changelog
22
All notable changes to this project will be documented in this file.
33

4-
## [4.0.3] - unreleased
4+
## [4.0.3] - 2024-01-17
55

6+
- 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)
67

78
## [4.0.2] - 2023-11-03
89

src/Eloquent/Model.php

+26
Original file line numberDiff line numberDiff line change
@@ -614,4 +614,30 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
614614

615615
return $attributes;
616616
}
617+
618+
/**
619+
* {@inheritDoc}
620+
*/
621+
public function save(array $options = [])
622+
{
623+
$saved = parent::save($options);
624+
625+
// Clear list of unset fields
626+
$this->unset = [];
627+
628+
return $saved;
629+
}
630+
631+
/**
632+
* {@inheritDoc}
633+
*/
634+
public function refresh()
635+
{
636+
parent::refresh();
637+
638+
// Clear list of unset fields
639+
$this->unset = [];
640+
641+
return $this;
642+
}
617643
}

tests/ModelTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -496,8 +496,10 @@ public function testUnset(): void
496496
$user1->unset('note1');
497497

498498
$this->assertFalse(isset($user1->note1));
499+
$this->assertTrue($user1->isDirty());
499500

500501
$user1->save();
502+
$this->assertFalse($user1->isDirty());
501503

502504
$this->assertFalse(isset($user1->note1));
503505
$this->assertTrue(isset($user1->note2));
@@ -526,6 +528,19 @@ public function testUnset(): void
526528
$this->assertFalse(isset($user2->note2));
527529
}
528530

531+
public function testUnsetRefresh(): void
532+
{
533+
$user = User::create(['name' => 'John Doe', 'note' => 'ABC']);
534+
$user->save();
535+
$user->unset('note');
536+
$this->assertTrue($user->isDirty());
537+
538+
$user->refresh();
539+
540+
$this->assertSame('ABC', $user->note);
541+
$this->assertFalse($user->isDirty());
542+
}
543+
529544
public function testUnsetAndSet(): void
530545
{
531546
$user = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);

0 commit comments

Comments
 (0)