Answer the question
In order to leave comments, you need to log in
How to mark all selected checkboxes if given 2 arrays?
Given: displaying categories in a loop:
foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
endforeach
@foreach($categories as $category)
@php $select = ''; @endphp
@foreach($post->categories as $category_item)
@if( $category->id == $category_item->id )
@php $select = 'selected'; @endphp
@break;
@endif
@endforeach
<option value="{{ $category->id }}" {{ $selected }}>{{ $category->name }}</option>
@endforeach
Answer the question
In order to leave comments, you need to log in
Two cycles are definitely not needed.
Somewhere you do this, a collection of IDs:
$postCategoriesIds = $post->categories->pluck('id')->all();
foreach($categories as $category)
<option value="{{ $category->id }}" @if($postCategoriesIds->contains($category->id)) selected @endif>{{ $category->name }}</option>
endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question