Trusted answers to developer questions

How to soft-delete a child model in Laravel

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Overview

Soft-deleting a model means flagging it as deleted when it’s still available in the database table. The deleted data still exists, but it can’t be seen or accessed by users.

You can refer to this shot for more information on soft-deleting.

Usage

Let’s say we have a post on a blog with several comments. The post is the parent model, while the comments are the child model. Now, suppose we don’t want a user to access the post comments that were just soft-deleted.

In this shot, we will use the Laravel soft-deletes-parent package.

Step 1: Package installation

Run the following composer command.

composer require 
dillingham/soft-deletes-parent

Step 2: Edit the table

You will need to add parent_deleted_at to the child table.

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

Use the code above in a new migration file so that the parent_deleted_at column will be added to the comments table.

Step 3: Add a trait

<?php

namespace App\Models;

use Dillingham\SoftDeletesParent\SoftDeletesParent;//Import this class
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use SoftDeletesParent;//traits added
}

The trait added above will enable the soft-delete so that any time a delete query is issued in the parent model, it will delete the corresponding child model.

Step 4: Register the application

To let your Laravel application know exactly what you want to do, you will need to register it in the AppServiceProvider class located in App/Providers, like so:

<?php

namespace App\Providers;

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

We have now successfully soft-deleted any Posts, and all the corresponding child comments will also be deleted.

RELATED TAGS

laravel
php

CONTRIBUTOR

Chinweuba Elijah Azubuike
Did you find this helpful?