L
L
lolrofl012021-04-24 18:33:57
Laravel
lolrofl01, 2021-04-24 18:33:57

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


The post has selected categories, they should be given 'selected'. But many categories can be selected for a post. Posts with categories are related, and when outputting $post->categories, a collection is displayed with the data of the categories that are selected for this post. The question is, is it possible to implement the idea without using 2 cycles?

This is the only option that comes to my mind, but I don't want to use 2 loops:
@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


A very crooked solution, but for some reason another does not come ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2021-04-24
@lolrofl01

Two cycles are definitely not needed.
Somewhere you do this, a collection of IDs:

$postCategoriesIds = $post->categories->pluck('id')->all();

Well, then you check whether the ID is included in that collection.
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 question

Ask a Question

731 491 924 answers to any question