#On delete cascade polymorphic relationship

7 messages · Page 1 of 1 (latest)

arctic yacht
#

Hey guys,

How can i delete a polymorphic relationship when the related model is deleted.
I do not care if it is at the database level or in the model, i just want to delete the relation in every model which is related to the polymorhpic model.

rough oyster
#

Hello @arctic yacht,

You want to delete or not delete the polymorphic models? You mentioned both.

I'm guessing you want to delete, this would be managed in the code and not the database.

You may use Laravel observers, inside the deleted function you can manually delete you le polymorphic relation. https://laravel.com/docs/9.x/eloquent#observers


public function deleted(User $user)
    {
        $user->tags()->delete();
         // this will bulk delete, no events will be thrown
        // So if you have another observer that needs to be called in the related model
       // You should do this 

        $user->tags()->each->delete()
    }

Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

arctic yacht
#

but i wanna watch for the related model when it is deleted, then to delete the polymorphic relationship

#

iykwim

#

also i corrected the mistake in the post sorry

rough oyster
#

Ah I think I understand.

Hum, I think my approach would be to keep the observer in your related model. Then, most relationships has a function you can call to detache the link.

Eg

Public function deleted(User $user)
{
    $user->tag()->detach(); // I know this would work for a belongsTo relationship
    

   // Perhaps this would work
   $user->tags()->sync([]);
}

I would need my computer to help you find the right function to call.

rough oyster
#

Ho, there might also be:

$user->tags()->dissociate()