Blog Detail

04

Nov
Soft Delete Child Models in Laravel When a Parent is Deleted cover image

arrow_back Soft Delete Child Models in Laravel When a Parent is Deleted

Soft delete is a useful feature of Laravel Eloquent. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted. You can view the documentation of Laravel Soft Delete here.

Brian Dillingham introduced a wonderful package called soft-deletes-parent that automatically soft delete a model’s children while maintaining their own soft-deleted state when you restore the parent model. After the installation, you’ve to add the SoftDeletesParent trait below, and 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 anywhere the parent is deleted.

Installation

You can install the package via composer by running this command:

composer require dillingham/soft-deletes-parent

Usage

After the installation, you’ve to add the parent_deleted_at column to your table:

Schema::table('posts', function (Blueprint $table) {
    $table->softDeletesParent();
});

Next, you’ve to add the trait and parent model to your child model:

<?php

namespace App\Models;

use Dillingham\SoftDeletesParent\SoftDeletesParent;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use SoftDeletesParent;
}
<?php

namespace App\Providers;

class AppServiceProvider
{
    public function register()
    {
        Post::softDeletesParent(Author::class);
    }
}

Scopes

With parent trashed:

Post::withParentTrashed()->get();

Only parent trashed:

Post::onlyParentTrashed()->get();

You can view the source code and other details of this package on Github.

Published at : 04-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project