Reputation: 270
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..
Upvotes: 0
Views: 1162
Reputation: 413
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.
Upvotes: 3