lighthouse icon indicating copy to clipboard operation
lighthouse copied to clipboard

Trigger model events on nested mutation delete of belongsTo relationships

Open skaesdorf opened this issue 1 year ago • 6 comments

  • [ ] Added or updated tests
  • [x] Documented user facing changes
  • [ ] Updated CHANGELOG.md

Changes

When deleting a model using a nested belongs to relation, the model will now be queried and then deleted. This ensures model events to be triggered.

Breaking changes

None.

skaesdorf avatar Jul 18 '24 11:07 skaesdorf

This would probably also apply to @delete when used as an ArgResolver. It also calls $relation->delete() or $related::destroy().

spawnia avatar Jul 19 '24 12:07 spawnia

True, but thats just the case for BelongsTo/HasOne. Other cases handled by $related::destroy() are fine since it queries the models. I commited the fix for BelongsTo/HasOne.

skaesdorf avatar Jul 19 '24 13:07 skaesdorf

Would it be simpler to let Laravel handle the fetching by using destroy() in all cases?

spawnia avatar Jul 19 '24 13:07 spawnia

I think thats not possible for HasOne since the id of the related model id is unknown. The id at this point is just nested inside a where condition of $relation->query. so, the related model has to be queried first to get the id. destroy() would query the model again.

skaesdorf avatar Jul 19 '24 13:07 skaesdorf

I just stumbled across an edgecase pitfall of destroy() that maybe should be considered.

destroy() itself is a static method, therefore only global scopes of the model may be respected. When a relation has a scope attached to it like this ...

    public function verifiedUsers () : BelongsTo
    {
        return $this->belongsTo( User::class )->onlyVerified();
    }

... it will not be respected since it is a) lost when calling $related = $relation->make(); and b) lost because destroy() is static. Therefore destroy() might not be a good idea at all? This allows cases where mutations are able to delete models that are not part of their scope.

skaesdorf avatar Jul 19 '24 13:07 skaesdorf

@spawnia Any thoughts? I would like to solve this.

skaesdorf avatar Aug 09 '24 13:08 skaesdorf