Skip to content

Commit 3a6df2e

Browse files
committed
Fix Model::unset with dot field name
1 parent e652b0c commit 3a6df2e

File tree

2 files changed

+47
-5
lines changed

2 files changed

+47
-5
lines changed

Diff for: src/Eloquent/Model.php

+10-5
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,16 @@ public function originalIsEquivalent($key)
315315
*/
316316
public function offsetUnset($offset): void
317317
{
318-
parent::offsetUnset($offset);
319-
320-
// Force unsetting even if the attribute is not set.
321-
// End user can optimize DB calls by checking if the attribute is set before unsetting it.
322-
$this->unset[$offset] = true;
318+
if (str_contains($offset, '.')) {
319+
// Update the field in the subdocument
320+
Arr::forget($this->attributes, $offset);
321+
} else {
322+
parent::offsetUnset($offset);
323+
324+
// Force unsetting even if the attribute is not set.
325+
// End user can optimize DB calls by checking if the attribute is set before unsetting it.
326+
$this->unset[$offset] = true;
327+
}
323328
}
324329

325330
/**

Diff for: tests/ModelTest.php

+37
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,43 @@ public function testUnset(): void
504504
$this->assertFalse(isset($user2->note2));
505505
}
506506

507+
public function testUnsetDotAttributes(): void
508+
{
509+
$user = User::create(['name' => 'John Doe', 'notes' => ['note1' => 'ABC', 'note2' => 'DEF']]);
510+
511+
$user->unset('notes.note1');
512+
513+
$this->assertFalse(isset($user->notes['note1']));
514+
$this->assertTrue(isset($user->notes['note2']));
515+
516+
$user->save();
517+
518+
$this->assertFalse(isset($user->notes['note1']));
519+
$this->assertTrue(isset($user->notes['note2']));
520+
521+
// Re-fetch to be sure
522+
$user = User::find($user->_id);
523+
524+
$this->assertFalse(isset($user->notes['note1']));
525+
$this->assertTrue(isset($user->notes['note2']));
526+
527+
// Unset the parent key
528+
$user->unset('notes');
529+
530+
$this->assertFalse(isset($user->notes['note1']));
531+
$this->assertFalse(isset($user->notes['note2']));
532+
$this->assertFalse(isset($user->notes));
533+
534+
$user->save();
535+
536+
$this->assertFalse(isset($user->notes));
537+
538+
// Re-fetch to be sure
539+
$user = User::find($user->_id);
540+
541+
$this->assertFalse(isset($user->notes));
542+
}
543+
507544
public function testUnsetAndSet(): void
508545
{
509546
$user = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);

0 commit comments

Comments
 (0)