Menu and child menu in laravel 5.1
-
So i have in my database a table with id, id_parent, title and so on.. I need to create a list with sublists from that. I need some sort of recursive function but don't know how to do that in laravel.. I tried class Goals extends Model { protected $table = 'goals'; public function subgoals() { return $this->hasMany(SubGoals::class, 'id_category'); } } class SubGoals extends Model { protected $table = 'goals'; public function goals() { return $this->belongsTo(Goals::class, 'id_category'); } } Controller: $treeView = Goals::with(['SubGoals'])->get(); And view: @foreach($treeView as $category) <li> <a href="#"> {{ $category->title }} </a> <ul> @foreach($category->subgoals as $subcategory) <li><a href="#">{{ $subcategory->title }}</a></li> @endforeach </ul> </li> @endforeach Didn't get the right result.. Maybe someone have a snippet..
-
Answer:
You dont need to create 2 classes, just need one like your example Goal. class Goal extends Model { protected $table = 'goals'; public function subgoals() { return $this->hasMany(Goal::class, 'parent_id', 'id'); } } then in the controller you need to "Query all parent Goals" like this: $parent_goals = Goal::whereNull('parent_id')->get(); and finally in the view: @foreach($parent_goals as $goal) <li> <a href="#"> {{ $goal->title }} </a> <ul> @foreach($goal->subgoals as $subgoal) <li><a href="#">{{ $subgoal->title }}</a></li> @endforeach </ul> </li> @endforeach that's it. hope that help's you.
Adrian C. at Stack Overflow Visit the source
Related Q & A:
- What is wrong with this Laravel 5 response?Best solution by Stack Overflow
- How to extend Laravel 5 auth properly?Best solution by Stack Overflow
- How do you get 5.1 surround sound through cable?Best solution by Yahoo! Answers
- What's the average/normal weight for a 13 year old girl who is 5'1?Best solution by Yahoo! Answers
- How do I hook up my computer to my 5.1 receivers?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.