<div class="col-lg-4">
<label for="referenceHarborId">{{ __('Porto de Referência') }}:</label>
<select id="referenceHarborId" class="form-control-custom select2">
<option></option>
@foreach($allHarbors as $harbor)
<option value="{{ $harbor->id }}" @if($referenceHarborId == $harbor->id){{ 'selected' }}@endif>
{{ $harbor->name }}
</option>
@endforeach
</select>
@error('referenceHarborId') <span class="error">{{ $message }}</span> @enderror
</div>
For initial value, a just verify if the value at the variable exist in the loop. And print ‘selected’.
Of course, to send the new value to Livewire component, and reload the form correctly after update, JS is necessary.
$(document).ready(function () {
$('#referenceHarborId').change(function (e) {
let elementName = $(this).attr('id');
@this.set(elementName, e.target.value);
});
});
document.addEventListener("livewire:load", function () {
window.livewire.hook('afterDomUpdate', () => {
$('#referenceHarborId').select2({
placeholder: 'Selecione uma opção',
width: '100%'
});
});
});
This way, I don’t need to trigger ‘change’.
But I already used something like you did. In some cases may be necessary.