I wanted to fetch nested categories data from a MySQL table in Laravel 7.
This is MySQL Table:
------------------------ |id | name | parent_id | |---|------|-----------| | 1 | A | NULL | |---|------|-----------| | 2 | B | NULL | |---|------|-----------| | 3 | C | NULL | |---|------|-----------| | 4 | a | 1 | |---|------|-----------| | 5 | ab | 4 | |---|------|-----------| | 6 | bc | 4 | |---|------|-----------| | 7 | ca | 4 | |---|------|-----------| | 8 | b | 2 | |---|------|-----------| | 9 | 2b | 8 | |---|------|-----------| |10 | 3b | 8 | |---|------|-----------| |11 | c | 3 | |---|------|-----------|
I want the following output:
A a ab bc ca B b 2b 3b C c
My Current Code (in controller) is:
public function sort_category($data, $opt){ $contents = Category::where('category_id', $data)->get(); foreach($contents as $c){ $opt .= "<option value='".$c->id."'>".$c->name."</option>"; $count = Category::where('category_id', $c->id)->count(); if($count > 0){ return $this->sort_category($c->id, $opt); } } return $opt; } public function add_category_form(){ $opt = ''; $html = $this->sort_category(NULL, $opt); return view('admin.add_category', ['categories' => $html]); }
Current Output:
A a ab bc ca
As you can see, it doesn’t iterate through B and C. Any help is appreciated.
Advertisement
Answer
You have a return statement inside the foreach loop.
This leads to a situation that only the first value with category_id
gets processed, not the others.
You should not return directly, but store the return values in an array for example, and return after the loop.