J
J
JohnDaniels2016-10-20 23:48:15
Laravel
JohnDaniels, 2016-10-20 23:48:15

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();

deletes only posts.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zlatoslav Desyatnikov, 2016-10-21
@JohnDaniels

As answered above, You
can call it conveniently using model events.
In your model:

// ...

public function boot()
{
     Post::deleted(function ($post) {
          $post->comments()->delete();
     });
}

Read more here:
https://laravel.com/docs/5.3/eloquent#events

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question