Unable to display a single instance of category, for multiple sub categories within the foreach loop

I have a has many through eloquent relationship, between Categories->SubCategories->MenuItems. I need to display a single category for all the sub categories which falls under the category in specific. Instead of my expectations, its showing the category above each and every sub-category. Sorry for being a noob, please help me.

Here’s what I have done so far.

<select wire:model="sub_category_id" class="form-select block w-full mt-1">
    <option>Select Sub Category</option>
    @foreach($menuitemlist as $menuitem)
    <optgroup label="{{ $menuitem->SubCategories->Categories->category_name }}">
        <option value="{{ $menuitem->SubCategories->id }}">{{ $menuitem->SubCategories->sub_category_name }}</option>
        @error('sub_category_id') <h1 class="text-red-500">{{$message}}</h1>@enderror

This is the output which I am getting. enter image description here

Just to explain what is going on here, you are creating an optgroup for every menu item, not every subcategory. Which means if two menu items are in the same subcategory, both with be in their own optgroups with the same name.

What you will need to look at here is a nested foreach loop. The outer loop is going to loop through the categories of the menuitem, the inner foreach is then going to loop through the subcategories of that category in the outer loop.

In the outer foreach loop you create your optgroup tag, since that loop is outputing categories. Here is some rough code to show you the idea…

@foreach($menucategories as $category)
    <optgroup label="{{ $category->name }}">
       @foreach($category->subcategories as $subcategory)
           <option value="{{ $subcategory->id }}">{{ $subcategory->name }}</option>

Now I know this isn’t exactly like what you have here, but I wanted to show you code to demonstrate the idea of what you need to do and how you go through the relationships. Your subcategories are children of categories.

If you are trying to go through the lowest level of this hierarchy by trying to work with menuitems directly, you have to find the way to reach up and loop on their parents and grandparents. I suspect that you can reach into the hierarchy a bit differently than you are now. If there is no other way, you have to decide how to detect when a menu items parent changes to know when to create a new optgroup tag. Remember, one optgroup tag per category, not per menuitem subcategory.

I hope you see what I am getting at here. :slight_smile:

1 Like

Perfect bro, this way worked like a charm, thanks alot bro! :slight_smile: