Using model events to delete related items

Submitted by msurguy - 10 years ago

Sometimes you might want to delete/update a whole lot of items that are related to a model when a record under that model is deleted from the database. This could be useful for various scenarios when there is a lot of processing that needs to be done upon model deletion. Laravel provides model events that you can use in that case.

// Model for the user
class User extends Eloquent{
    
    ...
    
    public static function boot()
    {
        parent::boot();
        
        // Attach event handler, on deleting of the user
        User::deleting(function($user)
        {   
            // Delete all tricks that belong to this user
            foreach ($user->tricks as $trick) {
                $trick->delete();
            }
        });
    }
    
    ...
}