Skip to content

Commit c57dd8e

Browse files
authored
Detach components from group on deletion via model event (#330)
1 parent 35b1f34 commit c57dd8e

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

src/Models/ComponentGroup.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ class ComponentGroup extends Model
4747
'visible',
4848
];
4949

50+
protected static function booted(): void
51+
{
52+
static::deleting(function (ComponentGroup $componentGroup): void {
53+
$componentGroup->components()->update(['component_group_id' => null]);
54+
});
55+
}
56+
5057
/**
5158
* Get the components in the group.
5259
*

tests/Unit/Models/ComponentGroupTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,28 @@
157157
// Should be expanded
158158
expect($group->fresh()->isExpanded())->toBeTrue();
159159
});
160+
161+
it('resets component_group_id on components when the group is deleted', function () {
162+
$group = ComponentGroup::factory()->hasComponents(2)->create();
163+
$componentIds = $group->components->pluck('id');
164+
165+
$group->delete();
166+
167+
foreach ($componentIds as $id) {
168+
$this->assertDatabaseHas('components', [
169+
'id' => $id,
170+
'component_group_id' => null,
171+
]);
172+
}
173+
});
174+
175+
it('does not delete components when the group is deleted', function () {
176+
$group = ComponentGroup::factory()->hasComponents(2)->create();
177+
$componentIds = $group->components->pluck('id');
178+
179+
$group->delete();
180+
181+
foreach ($componentIds as $id) {
182+
$this->assertDatabaseHas('components', ['id' => $id]);
183+
}
184+
});

0 commit comments

Comments
 (0)