Search code examples
phplaravel-5parent-childcategories

How to get a nested list of a child by Parent id?


I am using baum to get nested list of categories. I have a case where I only want to get a child of few parent id. I have used static function getNestedList("name", null, "   ") which gives me all categories nested list separated by space. I want the same response but only for few parent categories.

I tried below code to get my list with where clause but it only works with the first result. I have multiple parent_id and I need the each child listed in an array with space operator.

$node = Category::where('name', '=', 'Some category I do not want to see.')->first();

$root = Category::where('name', '=', 'Old boooks')->first();
var_dump($root->descendantsAndSelf()->withoutNode($node)->get());

QUESTION UPDATE

The issue I was facing to get descendants and self categories list using Baum was just because of wrong entry in my database. I am sorry for that. Now, I am getting my category list using descendantsAndSelf() but the issue is how to created the nested list with $seperator ?

I tried to toHierarchy() but it only return nested collection. I did not found any function which provides nested list like the function getNestedList("text", null, "   ");. Please help me on this.


Solution

  • UPDATED ANSWER

    As per my updated question, Below is my answer what I actually want to do.

    To get list of Descendants with parent I have used below function.

    public function getSubcategory($id) {
        $node = $this->where('id', $id)->with('children')->first();
        $descendant = $node->getDescendantsAndSelf()->toArray();
        return $this->CreateNestedList("text", $descendant, null, "-");
    }
    

    And to create nested loop I have used the same logic of the function getNestedList(). I have created new function inside my model file as below.

    public function CreateNestedList($column, $data, $key = null, $seperator = ' ') {
            $key = $key ?: $this->getKeyName();
            $depthColumn = $this->getDepthColumnName();
    
            return array_combine(array_map(function($node) use($key) {
              return $node[$key];
            }, $data), array_map(function($node) use($seperator, $depthColumn, $column) {
              return str_repeat($seperator, $node[$depthColumn]) . $node[$column];
            }, $data));
        }