skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. easy way you can delete first relation and after that del folder

    Folder::where('paren_id', $id)->delete();
    Folder::where('id', $id)->delete();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search