I'm having an error updating the checkbox when I return to the view containing it; in particular it always returns me the first checked checkbox but not the values selected before the update.
Can anyone help me to solve this problem?
<div >
<div for="treatment" >All treatments</div>
@foreach ($treatments as $treatment)
<input type="checkbox" id="{{$treatment->title}}" name="treatments[]" value="{{$treatment->id}}" {{ $treatment->id == 1 ? 'checked' : null }}>
<label for="{{$treatment->title}}"> {{$treatment->title}}</label><br>
@endforeach
</div>
CodePudding user response:
{{ $treatment->id == 1 ? 'checked' : null }}
In this code, you only added 'checked' attribute if the $treatment->id
is 1, so only the first checkbox will be checked.
@foreach ($treatments as $key => $treatment)
<input type="checkbox" id="{{$treatment->title}}" name="treatments[]" value="{{$treatment->id}}" {{ $treatment->id == $key ? 'checked' : null }}>
<label for="{{$treatment->title}}"> {{$treatment->title}}</label><br>
@endforeach
CodePudding user response:
I solved the following:
<div >
<div for="treatment" >All treatments</div>
@foreach ($treatments as $treatment)
<input type="checkbox" id="{{$treatment->title}}" name="treatments[]" value="{{$treatment->id}}" @if (count($quote->treatments->where('id', $treatment->id))) checked @endif>
<label for="{{$treatment->title}}"> {{$treatment->title}}</label><br>
@endforeach
</div>