Update / Delete associated related Models on Deletion in Laravel

Let’s just quickly go over on how easy it is to update / delete the related models in your Laravel Models using Model Events. Eloquent model dispatch several events based on the action performed on the model.

Let’s say you have a User model and associated Model named Post with One to Many relationship between the two.


    public function posts(){
        return $this->hasMany('App\Post');
    }

Let’s see how you can delete all posts on user deletion

Delete All Posts on Deleting User

Add a boot method to your User model and add the following snippet inside it


 public static function boot() {
    parent::boot();

    static::deleting(function($user) { // before delete() method call this
        $user->posts->each->delete();
    });
}

Update All Posts on Deleting User

If your requirement is to update all the posts on deleting the user, here is how you can accomplish it


public static function boot() {
    parent::boot();

    static::deleting(function($user) { // before delete() method call this
        $user->posts->each->update(['user_id' => NULL]);
    });
}

That’s all about updating / deleting the associated Models using Model Events in Laravel.

tgugnani: Web Stuff Enthusiast.