mehdi
mehdi

Reputation: 119

LARAVEL : SoftDelete all childs and their childs On SoftDelete a parent

i'm trying to make a dynamic treeview menu with one sql table based on parent_id method.

enter image description here

enter image description here

I could generate the treeview on my blade page and add new sections and childs.

my problem now is how can i softdelete all childs and sub childs when softdeleting a parent section ?

for exemple when deleting PHP section all childs and sub childs under PHP section must be deleted.

Thank you.

Upvotes: 2

Views: 1511

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

You can make use of the events provided by Laravel.

<?php

class Parent extends Model
{

    protected static function boot()
    {
        static::deleting(function ($instance) {
            $instance->child->each->delete();
        });

        static::restoring(function ($instance) {
            $instance->child->each->restore();
        });
    }
}

Then you do the same in your child class. When your $parent is soft deleted, it will soft delete all the child. Then the child will also soft delete all it's child.

For more information: https://laravel.com/docs/5.7/eloquent#events

Upvotes: 4

Related Questions