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
LeandroFerreira
LeandroFerreira3mo ago
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.
atabegruslan
atabegruslan3mo ago
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?
José Neto
José Neto3mo ago
Are you using soft delete on the Product model?
atabegruslan
atabegruslan3mo ago
No. Im not using soft deletes
Vp
Vp3mo ago
Try like this in DeleteAction
->after(function (Model $record) {
$record->relations()->delete();
})
->after(function (Model $record) {
$record->relations()->delete();
})
atabegruslan
atabegruslan3mo ago
Ok, but where should I write this code? In the resource file? or one of the files in Pages/?
Vp
Vp3mo ago
Delete action.. resource or pages where ever you put your action
atabegruslan
atabegruslan3mo ago
Yes, that worked, thank you And, how would this be written for DeleteBulkAction?
Vp
Vp3mo ago
Not sure about bulk action but it should be similar.. I think you can use inside ->action()
atabegruslan
atabegruslan3mo ago
I found out. It's quite similar. Instead of $record, the argument is an array of $records
Want results from more Discord servers?
Add your server