Do you have Cascade on delete set up https://laracasts.com/discuss/channels/laravel/laravel-delete-all-with-relation?page=1
Nov 4, 2019
9
Level 10
Laravel Delete All Related Rows not working
Hi, I have been looking up how to delete related rows and I am struggling to get it working. I have models Show and Tickets. I want to delete all tickets associated with shows when I delete a show. In my method I have
$event->shows()->whereNotIn('date', $request->dates)->delete();
and in my Show.php file I have
public function delete()
{
$this->tickets()->delete();
return parent::delete();
}
The show is deleted but the tickets still remain. The only thing I can think is that it is because I am calling the delete on $event->shows? If so, would I need to put the delete function on my Event.php file?
Level 10
I was able to get it working by adding this to my method
$showDelete = $event->shows()->whereNotIn('date', $request->dates)->get();
foreach($showDelete as $show){
$show->tickets()->delete();
}
$event->shows()->whereNotIn('date', $request->dates)->delete();
It's not the cleanest but it works.
Please or to participate in this conversation.