How to pass all categories and subcategories to layout laravel 9

Advertisements

I’m new to development, I ran into a problem, I can’t display all subcategories in the "layout.app" For each category, only one subcategory is displayed, and I need to get all subcategories

in file AppServiceProvider.php

 
public function boot()
{
    view()->composer('layout.app', function ($view){
        $view->with('categories', Category::with('subcategories')->get());
    });
}
in layout.app
<ul class="sub-category">
    @foreach($categories as $category)
    <li>
        <a href="{{ url('products') }}">{{ $category->title }}
            <i class="lni lni-chevron-right"></i>
        </a>
        @foreach($category->subcategories as $subcategory)
        <ul class="inner-sub-category">
            {{ $subcategory['title'] }}
        </ul>
        @endforeach
    </li>
    @endforeach
</ul>

>Solution :

I assume you’re receiving all the data.

And for sub-array, you need to define <ul> outside the foreach loop.

<ul class="inner-sub-category"> // Moved outside the foreach loop
    @foreach($category->subcategories as $subcategory)
        <li>{{ $subcategory['title'] }}</li>
    @endforeach
</ul>

Leave a ReplyCancel reply