I have a model CourseModule, and each of the items are related to the same model.
your model relationship should like this
// parent relation
public function parent(){
return $this->belongsTo(self::class , 'parent_id');
}
//child relation
public function children()
{
return $this->hasMany(self::class ,'parent_id');
}
public function ascendings()
{
$ascendings = collect();
$user = $this;
while($user->parent) {
$ascendings->push($user->parent);
if ($user->parent) {
$user = $user->parent;
}
}
return $ascendings;
}
public function descendings()
{
$descendings = collect();
$children = $this->children;
while ($children->count()) {
$child = $children->shift();
$descendings->push($child);
$children = $children->merge($child->children);
}
return $descendings;
}