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
onDeleteto 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_atfield 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:
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
Join the weekly newsletter and never miss out on new tips, tutorials, and more.
- Senior Laravel Engineer
Remote okay (must already live in USA)
- Senior Software Engineer (Remote - Contract)
- PHP Developer
Pittsburgh / Remote
Sequoia Waste Solutions
- Software Developer
- Application Developer Level II (CakePHP / MySql / Vue.js)
- FULL STACK LARAVEL DEVELOPER
LONDON - WEST END
- Mid/Senior Laravel Developer - U.S. Developers Only
Profit Miner Technologies
Running the Laravel Scheduler and Queue with Docker
In Laravel, one of the tricky changes when switching from a virtual server to Docker is figuring out how to run a sch…
Laravel 5.6.17 Released
Laravel v5.6.17 comes with helpers to make subquery joins more straightforward, along with a few minor changes and lo…