Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save marufsharia/9ed0072ec0031ed8b59c34328b9e1bbb to your computer and use it in GitHub Desktop.

Select an option

Save marufsharia/9ed0072ec0031ed8b59c34328b9e1bbb to your computer and use it in GitHub Desktop.
Select2 example with Livewire
<!-- Make sure jquery.js, Select2.js and Select2.css files are included (in master.blade.php or another template file) -->
<div>
<div wire:ignore>
<select class="select_country" wire:model="country">
<option value="" disabled>Please select the country</option>
@isset($this->countries)
@foreach(json_decode(json_encode($this->countries)) as $country)
<option value="{{ $country->code }}">{{ $country->name }}</option>
@endforeach
@endisset
</select>
</div>
<div>
<select class="select_state" wire:model="state">
<option value="" disabled>Please select the country first</option>
@isset($this->states)
@foreach(json_decode(json_encode($this->states)) as $state)
<option value="{{ $state->code }}">{{ $state->name }}</option>
@endforeach
@endisset
</select>
</div>
<script>
$(document).ready(function() {
$('select').select2();
});
$(window).on('refreshSelectBox', function(e) {
$('select').select2();
});
$('.select_country').on('change', function (e) {
@this.set('country', e.target.value);
});
$('.select_state').on('change', function (e) {
@this.set('state', e.target.value);
});
</script>
</div>
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class CountryAndState extends Component
{
public $countries = [], $states = [], $states_db = [];
public $country = '', $state = '';
public function boot()
{
// You don't need it in real use case. The states represent the object or database query you are looking for.
$this->states_db = [
['country' => 'US', 'code' => 'AL', 'name' => 'Alabama'],
['country' => 'US', 'code' => 'AK', 'name' => 'Alaska'],
['country' => 'US', 'code' => 'AZ', 'name' => 'Arizona'],
['country' => 'US', 'code' => 'AR', 'name' => 'Arkansas'],
['country' => 'CA', 'code' => 'AB', 'name' => 'Alberta'],
['country' => 'CA', 'code' => 'MB', 'name' => 'Manitoba'],
['country' => 'CA', 'code' => 'NU', 'name' => 'Nunavut'],
['country' => 'CA', 'code' => 'ON', 'name' => 'Ontario'],
];
}
public function mount()
{
$this->countries = [
['code' => 'US', 'name' => 'United States'],
['code' => 'CA', 'name' => 'Canada'],
['code' => 'AU', 'name' => 'Australia'],
['code' => 'NZ', 'name' => 'New Zealand'],
];
}
public function updatedCountry()
{
$this->state = '';
$this->states = collect($this->states_db)->where('country', $this->country)->all();
$this->dispatchBrowserEvent('refreshSelectBox');
}
public function updatedState()
{
$this->dispatchBrowserEvent('refreshSelectBox');
}
public function render()
{
return view('livewire.country-and-state');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment