Hi @alexteie
The thing with livewire is that when you have an array of checkboxes, they are sent like an associative array with the Model ID as the Key and true or false as the value, depending on the state of each checkbox.
So you'll receive something like this if you do a dd($this->selectedRoles) at the beginning of you save() method:
array:4 [▼
1 => false
2 => true
3 => false
4 => true
]
So, in order to make this work, at the mount() method, you need to form the array the same as it will be sent by livewire.
In my case this is what it worked:
public function mount() {
//
$this->selectedRoles = array_fill_keys($this->user->roles->pluck('id')->toArray(), true);
}
this will make the IDs the key of the array and fill the values with a true.
Then, at the moment of saving, since you need a simple array again, you have to go the other way around with something like this:
$this->user->syncRoles(array_keys(array_filter($this->selectedRoles)));
Finally, at the view you only need to wire the model like this (no name or value attributes needed):
@foreach ($roles as $role)
<div class="list-group-item">
<input type="checkbox" wire:model="selectedRoles.{{$role->id}}" class="form-checkbox">
<span>{{$role->display_name}} ({{$role->description}})</span>
</div><!-- list-group-item -->
@endforeach
Hope this works for you too!!