Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Akalanka1337's avatar

How to add optgroup in livewire blade file?

this $categories variable contains subCategories attribute, so i want to show sub categories under parent category.

$categories output sample:

Blade File:

                <div class="col-span-12">
                    <div class="w-full" wire:ignore>
                        <x-forms.select2
                            :label="__('messages.t_parent_category')"
                            :placeholder="__('messages.t_choose_parent_category')"
                            model="parent_id"
                            :options="$categories"
                            :isDefer="true"
                            :isAssociative="false"
                            :componentId="$this->id"
                            value="id"
                            text="name" />
                    </div>
                </div>
0 likes
2 replies
LaryAI's avatar
Level 58

To add optgroup in Livewire blade file, you can use the optgroup tag in the select element. Here's an example:

<select wire:model="parent_id">
    <option value="">Choose parent category</option>
    @foreach($categories as $category)
        <optgroup label="{{ $category['name'] }}">
            @foreach($category['subCategories'] as $subCategory)
                <option value="{{ $subCategory['id'] }}">{{ $subCategory['name'] }}</option>
            @endforeach
        </optgroup>
    @endforeach
</select>

In this example, we are using a nested foreach loop to iterate over the $categories array and its subCategories attribute. We are using the optgroup tag to group the subcategories under their parent category. The label attribute of the optgroup tag is set to the parent category name. The value attribute of the option tag is set to the subcategory ID, and the text between the opening and closing option tags is set to the subcategory name.

Akalanka1337's avatar

@LaryAI useful but its not with select2 option. , also i want to select main category as well.

Please or to participate in this conversation.