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

phayes0289's avatar

How To Group Query Results By Category and Display The Cat. in Select2

I have data in a MySQL table that has a name, value and group field. The following is a screenshot of the data table.

https://www.screencast.com/t/777cLTbhHC

I want to output the table into a Select2 select field so that it looks like the code below where the optgrpup label equals the group name; and the options names and values equal the data from the table rows.

<select class="select2 form-control w-100" id="single-default">
                                        <optgroup label="Alaskan/Hawaiian Time Zone">
                                            <option value="AK">Alaska</option>
                                            <option value="HI">Hawaii</option>
                                        </optgroup>
                                        <optgroup label="Pacific Time Zone">
                                            <option value="CA">California</option>
                                            <option value="NV">Nevada</option>
                                            <option value="OR">Oregon</option>
                                            <option value="WA">Washington</option>
                                        </optgroup>
 </select>

Do I need to do something special to the database query like grouping data? And how would I output the outgroup.

Thanks.

0 likes
2 replies
kokoshneta's avatar
Level 27

Just group the collection after fetching the data – that will give you (opt)groups containing options.

Haven’t tested, but something like this should work:

In your controller (or wherever you’re defining your data):

$data = Pibs::all()
	->get()
	->groupBy('group')
;

In your Blade template:

<select class="select2 form-control w-100" id="single-default">
	@foreach ($data as $group => $options)
		<optgroup label="{{ $group }}">
			@foreach ($options as $option)
				<option value="{{ $option->value }}">{{ $option->name }}</option>
			@endforeach
		</optgroup>
	@endforeach
</select>

Please or to participate in this conversation.