Recursively delete categories in laravel

Viewed 22

I've already one solution that works for my problem but i just want to know if you think there is a better solution.

I've got a function that works in the model for recursively get the parents of one category :

    public function parent()
{
    return $this->belongsTo(ProductCat::class, 'parent_id');
}

public function getAllParents()
{
    $parents = collect([]);
    $parent = $this->parent;

    while(!is_null($parent)) {
        $parents->push($parent);
        $parent = $parent->parent;
    }

    return $parents;
}

I want to do the same for the childs, so i've tried this :

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

public function getAllChilds()
{
    $childs = collect([]);
    $child = $this->children;

    while(!is_null($child)) {
        $childs->push($child);
        $child = $child->child;
    }

    return $childs;
}

But i get an error like : child dont exist in that collection on this line : $child = $child->child;

So i've worked on a different way that is functionning:

    public function hasChilds($id) 
{
    $req = $this->model->find($id)->children;
    if($req->count() > 0)
        return $req;
    return false;
}   

public function destroy($id)
{
    if($childs = $this->hasChilds($id))
    {
        foreach($childs as $child)
        {
            //$childs = $this->model->find($id)->getAllChilds()->reverse();
            $this->destroy($child->id);
            $this->model->destroy($child->id);
        }
    }
    
    $this->model->destroy($id);
}

But i think that do it in the model is a better way !

What do you think ? Thanks in advance all !

0 Answers
Related