diff --git a/src/Models/Concerns/HasFlags.php b/src/Models/Concerns/HasFlags.php index 4c34418..d7118b8 100644 --- a/src/Models/Concerns/HasFlags.php +++ b/src/Models/Concerns/HasFlags.php @@ -5,10 +5,18 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\MorphMany; use Spatie\ModelFlags\Models\Flag; +use Illuminate\Database\Eloquent\Model; -/** @mixin \Illuminate\Database\Eloquent\Model */ +/** @mixin Model */ trait HasFlags { + public static function bootHasFlags() + { + static::deleted(function (Model $deletedModel) { + $deletedModel->flags()->delete(); + }); + } + public function flags(): MorphMany { return $this->morphMany(config('model-flags.flag_model'), 'flaggable'); diff --git a/tests/HasFlagsTest.php b/tests/HasFlagsTest.php index dd3a311..766d7f9 100644 --- a/tests/HasFlagsTest.php +++ b/tests/HasFlagsTest.php @@ -76,3 +76,15 @@ $this->otherModel->flag('flag-a'); expect(TestModel::notFlagged('flag-a')->get())->toHaveCount(0); }); + +it('can_remove_flags_on_model_delete', function () { + $this->model->flag('flag-a'); + + $this->model->delete(); + + $this->assertEquals(0, $this->model->flags()->get()->count()); +}); + +it('can_remove_model_without_flags', function () { + expect($this->model->delete())->toBeTrue(); +});