Answer the question
In order to leave comments, you need to log in
How to remove related models in Laravel?
Let's say there are Post and Comment models, a one-to-many relationship.
Is there a way to "out of the box" remove all related comments when deleting a post?
Tried
Post::with('comments')->where('id', '=', $id)->delete();
Answer the question
In order to leave comments, you need to log in
As answered above, You
can call it conveniently using model events.
In your model:
// ...
public function boot()
{
Post::deleted(function ($post) {
$post->comments()->delete();
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question