Created
December 17, 2025 14:25
-
-
Save MiloudiMohamed/5bd253b23fe09326ce7c95cb814fe777 to your computer and use it in GitHub Desktop.
Select2 with Livewire + AlpineJS implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {{-- Usage with Livewire --}} | |
| <x-select2 | |
| name="user_id" | |
| multiple | |
| wire:model.live="userId" | |
| :options="User::pluck('name', 'id')->toArray()" | |
| /> | |
| {{-- Usage with AlpineJS --}} | |
| <div | |
| x-data="{ | |
| user_id: null | |
| }" | |
| > | |
| <x-select2 | |
| name="user_id" | |
| multiple | |
| x-model="user_id" | |
| :options="User::pluck('name', 'id')->toArray()" | |
| /> | |
| </div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @props([ | |
| 'name' => null, | |
| 'options' => [], | |
| 'multiple' => false, | |
| 'placeholder' => __('Sélectionnez une option'), | |
| ]) | |
| <div | |
| x-data="{ | |
| options: @js($options), | |
| init () { | |
| this.$nextTick(() => { | |
| this.$dispatch('options-changed', this.options); | |
| }) | |
| } | |
| }" | |
| > | |
| <div | |
| wire:ignore | |
| x-data="{ | |
| select: null, | |
| options: [], | |
| value: null, | |
| init() { | |
| this.$nextTick(() => { | |
| this.select = $(this.$refs.select).select2() | |
| this.select.on('change', (e) => { | |
| this.value = $(e.target).val() | |
| this.$dispatch('input', this.value) | |
| }) | |
| }) | |
| }, | |
| setOptions(values) { | |
| this.options = values | |
| this.value = null | |
| } | |
| }" | |
| @options-changed.window="setOptions($event.detail)" | |
| x-modelable="value" | |
| {{ $attributes }} | |
| > | |
| <select | |
| x-ref="select" | |
| data-placeholder="{{ $placeholder }}" | |
| class="select2 w-100" | |
| @if($multiple) multiple @endif | |
| > | |
| @if(!$multiple) | |
| <option value="" selected>{{ $placeholder }}</option> | |
| @endif | |
| <template x-for="[id, name] in Object.entries(options)" :key="id"> | |
| <option :value="id" x-text="name"></option> | |
| </template> | |
| </select> | |
| <template x-if="Array.isArray(value)"> | |
| <template x-for="v in value" :key="v"> | |
| <input type="hidden" name="{{ $name }}[]" :value="v"> | |
| </template> | |
| </template> | |
| <template x-if="!Array.isArray(value)"> | |
| <input type="hidden" name="{{ $name }}" :value="value"> | |
| </template> | |
| </div> | |
| </div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment