Cascading Soft Deletes with Laravel 5

Cascading Soft Deletes with Laravel 5

Laravel Soft Cascade is a package that makes it easy to perform soft cascade deletes and restores on related models using soft deleting.

Contributor to the package Will Bowman wrote about his package and what happens to the foreign key constraints you want to cascade delete related models, but you have configured soft deletes:

I’ve always used MySQL foreign key constraints to cascade delete related records. Laravel makes it easy to use foreign keys in migrations, set onDelete to cascade and walla, your relations will be deleted automatically.

But what happens when you enable SoftDeletes? Your database is never told to actually ‘delete’ a record, instead the deleted_at field is updated. So what happens to your cascading deletes? Nothing, your related records are left alone.

His post shows an overview of the approach he takes with his package, specifically making it easy to configure cascading deletes without a bunch of boilerplate code:

My solution was to use Events and an array in the Model to tell it what to cascade, this allows us to simply add 2 lines to a Model to enable cascade deleting and restoring:

Using the package, you can enable the SoftCascadeTrait and configure which relationships should soft cascade delete:

use \Askedio\SoftCascade\Traits\SoftCascadeTrait;

protected $softCascade = ['profiles'];

After defining your relations, you can trigger a delete or a restore on your model and related models will be restored or deleted (soft) along with the model:

User::first()->delete();
User::withTrashed()->first()->restore();

Learn More

To get started, install the package with composer and auto-discovery in Laravel will take care of the rest:

composer require askedio/laravel-soft-cascade

Check out the GitHub repo and Will Bowman’s post for more information.


Filed in: Laravel Packages / Eloquent


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Software Engineer Lead (PHP)
Remote
CivicPlus, LLC
Full-time Senior Web Developer
Detroit, MI
Wayne State University
Senior Software Engineer
Sydney, Australia
FoodByUs
Full Stack Engineer
Remote or Medford, Oregon
Empire Medical
Laravel Developer (fulltime - Dutch only)
Netherlands
Qbixx | Webservices
Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Senior Quality Assurance Engineer
Remote
Bisnow Media