Laravel returning children of parents in same table
First of all, what you are doing is inefficient. Your view iterates through all subcategories for every parent category. If you defined relations properly and made use of Eloquent's eager loading, you could fetch and access child categories in easier way.
Start with defining relations:
class Category extends Model {
//each category might have one parent
public function parent() {
return $this->belongsToOne(static::class, 'cat_parent_id');
}
//each category might have multiple children
public function children() {
return $this->hasMany(static::class, 'cat_parent_id')->orderBy('cat_name', 'asc');
}
}
Once you have the relations defined properly, you can fetch whole category tree like below:
view()->composer('partials.header', function($view) {
$view->with('categories', Category::with('children')->whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
The second composer won't be needed, as parent categories already contain children.
Now, you only need to display the categories in your view:
<ul>
@foreach ($categories as $parent)
<li>{{ $parent->cat_name }}
@if ($parent->children->count())
<ul>
@foreach ($parent->children as $child)
<li>{{ $child->cat_name }}</li>
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>