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

Livewire Component Library

 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

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

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.

Site Footer