Handling circular soft deletes for two models

  eloquent, laravel

I have two models (Owner and Car), with an one to one relationship between them. Both models use soft deletes. If either model is soft deleted, it should soft delete it’s relation.

Currently, when Owner is deleted, I use events to delete Car:

App/Models/Owner

protected static function booted()
{
    static::deleted(function ($owner) {
        $owner->car->delete();
    });

    static::restored(function ($owner) {
        $owner->car()->withTrashed()->first()->restore();
    });
}

This works fine, but I can’t work out how to do the same from Car without running into circular logic. I have tried adding a logical test for $car->owner or $car->owner()->trashed() but in both cases the page just hangs – presumably as the methods are going in a circle.

How can I achieve the desired behaviour?

Source: Laravel

Leave a Reply