Home > Software engineering >  Laravel delete all rows related to one another in the same table
Laravel delete all rows related to one another in the same table

Time:01-23

Here i have folders table that contains folder information like name etc. all folder may have some sub folders. when i want to remove the parent folder i need to delete all the sub folders and all sub sub folders under sub folders.

enter image description here

for example in the picture if i delete folder id 1, it must delete folder id 4, 5, 6, 7, 8, 9 and 10. because all the folders are inside folder id 1.

i think i made you understand.

Folder::where('id', $id)->delete();

This delete only to folder with the given id, not the sub folders

Thanks all

CodePudding user response:

You can define deleting in the Folder model. I suppose that you also defined the relation

public function subfolders() {
    return $this->hasMany(Folder::class, 'parent_id');
}

So you should add this to your Folder model:

public static function boot () {
    parent::boot();

    self::deleting(function ($folder) {
        foreach ($folder->subfolders as $subfolder) {
            $subfolder->delete();
        }
    });
}

This will be triggered on delete action and will delete all the subfolders, deleting of each of them will also run this function etc.

  • Related