Delete relations when delete a model
How do you do this?
Currently only the immediate model in question gets deleted, all its relations still hangs in the DB like ghosts
10 Replies
Laravel - The PHP Framework For Web Artisans
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.
Actually, no, I encountered issues with this solution. I re-opened this Q
Lets say, I got Product, which can have many Variants.
It is not sensible to declare a foreign-key in Product thats points to all its Variants.
It's better to have a foreign-key field in each Variant.
Now the problem is, in the Variant's migration file, if I write this:
$table->foreignId('product_id')->onDelete('cascade');
then when I delete the Product, the Variants stay.
It's only when I delete a variant, then would the Product will be deleted too. <--- This is the opposite of what I want.
So I want to ask, is there another way?Are you using soft delete on the Product model?
No. Im not using soft deletes
Try like this in DeleteAction
Ok, but where should I write this code?
In the resource file? or one of the files in
Pages/
?Delete action.. resource or pages where ever you put your action
Yes, that worked, thank you
And, how would this be written for
DeleteBulkAction
?Not sure about
bulk action
but it should be similar.. I think you can use inside ->action()
I found out. It's quite similar.
Instead of
$record
, the argument is an array of $records