motinska94's avatar

Any way to detect a detach?

I have a Post model with many-to-many Tag relationships, and while detaching a tag from a post, I want to check if that tag is connected to any other post and remove it if it's not. Is there a way to do it? Here's what I want to happen in pseudo-code :

// App/Models/Post.php

protected static function boot(){
   static::detaching(function(Post $post, Tag $tag){
      if(!$tag->has('posts')){
         $tag->delete();
      }
   });
}
0 likes
2 replies
martinbean's avatar
Level 80

@motinska94 Not really, as no event is raised when attaching or detaching many-to-many records.

1 like
motinska94's avatar

@martinbean Thanks! Chatgpt suggested me to make a new model for the pivot relationship and call the logic on the pivot's static::deleting action.

I don't feel like it's the best way to handle it but since I'm the only admin of this blog it should be fine if it's not perfectly optimized.

Please or to participate in this conversation.