Soft Delete Child Models When a Parent is Deleted
Published on by Paul Redmond
Laravel Soft Deletes Parent is a package by Brian Dillingham that soft deletes child models when a parent model is soft-deleted:
Automatically soft delete a model's children while maintaining their own soft-deleted state when you restore the parent model. After installing the trait below, the
Post
model'sparent_deleted_at
will update whenever anAuthor
model is deleted or restored. This allows you to maintain the originaldeleted_at
for thePost
model afterAuthor
is restored. ThePost
model will scope queries to exclude any where the parent is deleted.
To use this package, you'll want to add a parent_deleted_at
column on the child database table (this package provides a migration helper to generate the correct column), add a trait to the child model, and register parent models.
Given a parent Author
model and a child Post
model, here's how you'd set it up:
// Use the `SoftDeletesParent` trait on the child model.namespace App\Models; use Dillingham\SoftDeletesParent\SoftDeletesParent;use Illuminate\Database\Eloquent\Model; class Post extends Model{ use SoftDeletesParent;} // Register parent modelsclass AppServiceProvider{ public function register() { Post::softDeletesParent(Author::class); }}
Now you can query with provided scopes
// Get all posts, including soft-deleted records.Post::withParentTrashed()->get(); // Get soft-deleted posts.Post::onlyParentTrashed()->get();
You can learn more about this package, get full installation instructions, and view the source code on GitHub.