This repository contains some useful collection macros for Select2.
You can pull in the package via composer:
composer require yneet/laravel-collection-select2
The package will automatically register itself.
Transform the collection inline to grouped for Select2 Ajax/Data format (see : https://select2.org/data-sources/formats#grouped-data).
$collection = collect([
['text' => 'Title 1', 'id' => 1, 'group' => 'Group 1'],
['text' => 'Title 2', 'id' => 2, 'group' => 'Group 1'],
...
]);
$collection->toSelect2Grouped('group');
// [
// [
// 'text' => 'Group 1',
// 'children' => [
// ['text' => 'Title 1', 'id' => 1, 'group' => 'Group 1'],
// ['text' => 'Title 2', 'id' => 2, 'group' => 'Group 1']
// ]
// ],
// ...
// ];
The MIT License (MIT). Please see License File for more information.