Skip to content

Instantly share code, notes, and snippets.

@amrography
Created July 6, 2020 17:25
Show Gist options
  • Save amrography/c1b8fc8c6486301fab73b2e93cbbdc4c to your computer and use it in GitHub Desktop.
Save amrography/c1b8fc8c6486301fab73b2e93cbbdc4c to your computer and use it in GitHub Desktop.
Livewire select drop menu example
{{-- file path, resources/views/livewire/select-city.blade.php --}}
<div>
<div class="form-group">
<label for="country">Select country</label>
<select class="form-control" wire:model="selectedCountry" name="country" id="country">
@foreach ($countries as $country)
<option value="{{$country}}">{{$country}}</option>
@endforeach
</select>
<p>Selected country {{ $selectedCountry }}</p>
</div>
<div class="form-group">
<label for="city">Select city</label>
<select class="form-control" wire:model="selectedCity" name="city" id="city">
@foreach ($cities as $key => $city)
<option value="{{$city}}">{{$city}}</option>
@endforeach
</select>
<p>Selected city {{ $selectedCity }}</p>
</div>
<div wire:loading>
Loading...
</div>
</div>
<?php
// file path, app/Http/Livewire/SelectCity.php
namespace App\Http\Livewire;
use Livewire\Component;
class SelectCity extends Component
{
public $countries;
public $cities;
public $selectedCountry = 'Egypt';
public $selectedCity;
public function mount()
{
$this->countries = [
'Egypt',
'Kuwait',
'UAE'
];
}
public function render()
{
$this->cities = $this->getCityByCountry();
return view('livewire.select-city');
}
private function getCityByCountry()
{
switch (strtolower($this->selectedCountry)) {
case 'egypt': $cities = ['Egypt city 1', 'Egypt city 2', 'Egypt city 3']; break;
case 'kuwait': $cities = ['Kuwait city 1', 'Kuwait city 2', 'Kuwait city 3']; break;
case 'uae': $cities = ['UAE city 1', 'UAE city 2', 'UAE city 3']; break;
default: $cities = []; break;
}
// Pre-select city for better UI looking
$this->selectedCity = $cities[0];
return $cities;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment