Soft Delete Child Models When a Parent is Deleted

Packages

October 26th, 2021

laravel-parent-soft-delete.png

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's parent_deleted_at will update whenever an Author model is deleted or restored. This allows you to maintain the original deleted_at for the Post model after Author is restored. The Post 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:

1// Use the `SoftDeletesParent` trait on the child model.
2namespace App\Models;
3 
4use Dillingham\SoftDeletesParent\SoftDeletesParent;
5use Illuminate\Database\Eloquent\Model;
6 
7class Post extends Model
8{
9 use SoftDeletesParent;
10}
11 
12// Register parent models
13class AppServiceProvider
14{
15 public function register()
16 {
17 Post::softDeletesParent(Author::class);
18 }
19}

Now you can query with provided scopes

1// Get all posts, including soft-deleted records.
2Post::withParentTrashed()->get();
3 
4// Get soft-deleted posts.
5Post::onlyParentTrashed()->get();

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.