diff --git a/src/Models/ComponentGroup.php b/src/Models/ComponentGroup.php index 3a72da1a..92ef0a06 100644 --- a/src/Models/ComponentGroup.php +++ b/src/Models/ComponentGroup.php @@ -47,6 +47,13 @@ class ComponentGroup extends Model 'visible', ]; + protected static function booted(): void + { + static::deleting(function (ComponentGroup $componentGroup): void { + $componentGroup->components()->update(['component_group_id' => null]); + }); + } + /** * Get the components in the group. * diff --git a/tests/Unit/Models/ComponentGroupTest.php b/tests/Unit/Models/ComponentGroupTest.php index df603bb4..5a34891b 100644 --- a/tests/Unit/Models/ComponentGroupTest.php +++ b/tests/Unit/Models/ComponentGroupTest.php @@ -157,3 +157,28 @@ // Should be expanded expect($group->fresh()->isExpanded())->toBeTrue(); }); + +it('resets component_group_id on components when the group is deleted', function () { + $group = ComponentGroup::factory()->hasComponents(2)->create(); + $componentIds = $group->components->pluck('id'); + + $group->delete(); + + foreach ($componentIds as $id) { + $this->assertDatabaseHas('components', [ + 'id' => $id, + 'component_group_id' => null, + ]); + } +}); + +it('does not delete components when the group is deleted', function () { + $group = ComponentGroup::factory()->hasComponents(2)->create(); + $componentIds = $group->components->pluck('id'); + + $group->delete(); + + foreach ($componentIds as $id) { + $this->assertDatabaseHas('components', ['id' => $id]); + } +});