'Multiple Selection field is blank in edit form, Select2 in edit form not triggering the selected values in edit form- Laravel Livewires
I have a select2 in a livewire component. Everything works fine but in my edit view, the selected options don't show in the box is selected. When I open the dropdown they show as highlighted, so data is coming from the backend. Please check below codes and output screenshots, Thanks in advance for your kind help.
Livewire Component
public $home_categories = [];
public $no_of_products;
public function mount()
{
$category = HomeCategory::all()->first();
$this->home_categories = explode(',', $category->home_categories);
$this->no_of_products = $category->no_of_products;
}
Blade Component:
<div class="form-group">
<label for="home_categories" class="col-md-4 control-label">Choose Category</label>
<div class="col-md-6" wire:ignore>
<select class="select2 form-control" name="home_categories[]" multiple="multiple" wire:model="home_categories">
@foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
The script inside the livewire:
@push('scripts')
<script>
$(document).ready(function() {
$('.select2').select2();
$('.select2').on('change', function (e) {
var data = $('.select2').select2("val");
@this.set('home_categories', data);
});
});
</script> @endpush
Solution 1:[1]
Use this code inside the blade components:
@if (in_array($category->id, $home_categories)) {{'selected'}} @endif
The script, component properties everything As-It-Is only changes in select option tag: like below code:
<select class="select2 form-control" name="home_categories[]" multiple="multiple" wire:model="home_categories">
@foreach ($categories as $category)
<option value="{{$category->id}}" @if (in_array($category->id, $home_categories)){{'selected'}}
@endif>{{$category->name}}</option>
@endforeach
Solution 2:[2]
In you component
public function hydrate(){$this->emit('data');}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Bharath |
| Solution 2 | Unseen Assasin |


