@govindalohani I would suggest a modification to your data structure, even in the best case scenario you are still doing "n + 1" queries by getting each children in a recursive call.
I would suggest creating another parallel table with: parent_id, child_id, depth. Store all children of a parent and increase the depth for each recursive call. This way when you call ->children() you get children of all levels.
Want first order children only, do: ->children()->where('depth', 0).
Want all parents of an item: ->parents().
Configure parents relation such as:
public function parents(): BelongsToMany
{
return $this->belongsToMany(
__CLASS__,
'pivot_table_name',
'child_id',
'parent_id'
)
->withTimestamps()
->withPivot('depth') // order parents by depth (asc), first parent is also direct parent
->orderBy('pivot_table_name.depth');
}