Installation:
composer require pharaonic/livewire-select2
Publish the config (optional):
php artisan vendor:publish --provider="Pharaonic\LivewireSelect2\ServiceProvider"
Basic Usage:
use Pharaonic\LivewireSelect2\LivewireSelect2;
public function mount()
{
$this->options = [
'id' => 'my-select',
'label' => 'Choose an option',
'options' => [
['id' => 1, 'text' => 'Option 1'],
['id' => 2, 'text' => 'Option 2'],
],
];
}
public function render()
{
return LivewireSelect2::make('options');
}
Blade Integration:
@livewireSelect2('options', 'my-component')
Replace a standard <select> dropdown with a Searchable, Taggable, and Customizable Select2 component in a Livewire form. Ideal for:
Dynamic Data Binding:
// Fetch data from DB and bind to Select2
public function mount()
{
$this->users = User::all()->pluck('name', 'id');
$this->options = [
'label' => 'Select User',
'options' => $this->users,
'wire:model' => 'selectedUserId',
];
}
Multi-Select with Tags:
$this->options = [
'label' => 'Select Tags',
'options' => Tag::all()->pluck('name', 'id'),
'multiple' => true,
'tags' => true, // Enable tagging new options
];
Remote Data Fetching:
// Use `wire:model.live` for debounced search
$this->options = [
'label' => 'Search Products',
'url' => route('api.products.search'),
'minimumInputLength' => 2,
'placeholder' => 'Type to search...',
];
protected $rules = ['selectedUserId' => 'required|exists:users,id'];
/* resources/css/select2-custom.css */
.select2-container--default .select2-selection--single {
border: 1px solid #ccc;
}
select2:select or select2:unselect:
public function updatedSelectedUserId($value)
{
$this->emit('userSelected', $value);
}
JavaScript Conflicts:
$this->options['id'] = 'unique-select-' . uniqid();
AJAX Caching:
url) may cache responses. Use cache: false in config or append a timestamp:
$this->options['url'] = route('api.products.search') . '?t=' . time();
Livewire Model Binding:
wire:model is an array:
public $selectedTags = [];
$this->options['wire:model'] = 'selectedTags';
Uncaught ReferenceError if Select2 JS fails to load.php artisan config:clear
Custom Templates: Override Select2 templates via config:
'templates' => [
'result' => '<div class="custom-result">{{ $data.text }}</div>',
],
Event Extensions:
Extend core events (e.g., select2:initialized) via Livewire hooks:
protected $listeners = ['select2:initialized' => 'handleSelect2Init'];
public function handleSelect2Init()
{
$this->dispatch('select2Ready');
}
Server-Side Processing:
Use ajax config for complex queries:
$this->options['ajax'] = [
'url' => route('api.users.search'),
'dataType' => 'json',
'delay' => 250,
'data' => function($params) {
return ['q' => $params['term']];
},
'processResults' => function($data) {
return [
'results' => array_map(fn($user) => [
'id' => $user['id'],
'text' => $user['name'],
], $data['users']),
];
},
];
How can I help you explore Laravel packages today?