Home > Software engineering >  How to pass all categories and subcategories to layout laravel 9
How to pass all categories and subcategories to layout laravel 9

Time:12-19

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 >
    @foreach($categories as $category)
    <li>
        <a href="{{ url('products') }}">{{ $category->title }}
            <i ></i>
        </a>
        @foreach($category->subcategories as $subcategory)
        <ul >
            {{ $subcategory['title'] }}
        </ul>
        @endforeach
    </li>
    @endforeach
</ul>

CodePudding user response:

I assume you're receiving all the data.

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

<ul > // Moved outside the foreach loop
    @foreach($category->subcategories as $subcategory)
        <li>{{ $subcategory['title'] }}</li>
    @endforeach
</ul>
  • Related