This is my component:
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Departamento;
use App\Models\Provincia;
use App\Models\Distrito;
class UbigeoSelector extends Component
{
public $departamento_id, $provincia_id, $distrito_id;
public $provincias = [];
public $distritos = [];
public function mount($departamento_id = null, $provincia_id = null, $distrito_id = null)
{
$this->departamento_id = $departamento_id;
$this->provincia_id = $provincia_id;
$this->distrito_id = $distrito_id;
}
public function render()
{
return view('livewire.ubigeo-selector', [
'departamentos' => Departamento::all(),
'provincias' => $this->provincia_id ? Provincia::where('departamento_id', $this->departamento_id)->get() : [],
'distritos' => $this->distrito_id ? Distrito::where('provincia_id', $this->provincia_id)->get() : [],
]);
}
public function updatedDepartamentoId($value)
{
logger()->info('Departamento actualizado: ' . $value);
$this->provincia_id = null;
$this->distrito_id = null;
$this->provincias = Provincia::where('departamento_id', $value)->get();
}
public function updatedProvinciaId($value)
{
$this->distrito_id = null;
$this->distritos = Distrito::where('provincia_id', $value)->get();
}
}
This is the view of my component, which only shows a select field and when selecting an option it should activate the following select field
<div>
<div>
<label for="departamento">Departamento</label>
<select wire:model="departamento_id" id="departamento">
<option value="">Seleccione un departamento</option>
@foreach($departamentos as $departamento)
<option value="{{ $departamento->id }}" @if($departamento->id == $departamento_id) selected @endif>{{ $departamento->nombre }}</option>
@endforeach
</select>
</div>
@if($departamento_id)
<div>
<label for="provincia">Provincia</label>
<select wire:model="provincia_id" id="provincia">
<option value="">Seleccione una provincia</option>
@foreach($provincias as $provincia)
<option value="{{ $provincia->id }}" @if($provincia->id == $provincia_id) selected @endif>{{ $provincia->nombre }}</option>
@endforeach
</select>
</div>
@endif
@if($provincia_id)
<div>
<label for="distrito">Distrito</label>
<select wire:model="distrito_id" id="distrito">
<option value="">Seleccione un distrito</option>
@foreach($distritos as $distrito)
<option value="{{ $distrito->id }}" @if($distrito->id == $distrito_id) selected @endif>{{ $distrito->nombre }}</option>
@endforeach
</select>
</div>
@endif
</div>
The way it works should be that when selecting an option from the "Departments" part it should render showing me in the second select the "Provinces" of the selected "Department" but the wire:model does not activate anything
In Livewire 3 wire:model is deferred by default. To obtain an immediate call to the backend you must use the live modifier:
<select wire:model.live="provincia_id" id="provincia">
.....
</select>