Anik Anik - 3 months ago 14
PHP Question

Checking which options are already selected from multi select box laravel loop in view

I am having problem with looping. I am passing all categories and category that the post has in two arrays.

$cat = [1,2,3,4] // category ids
$catOfPost = [2,3] // the post has these categories already

Now I created a select box with option filed populated from $cat.
Now I want to attach class to option which have id matching to $catOfPost.

I have tried following.

<select name="test[]">
@for($i = 0; $i< count($cat); $i++)
@for($x=0; $x < count($catOfPost); $x++)
<option
@if($catOfPost[$x]->id == $cat[$i]->id )
class="test"
@endif
value="{{$cat[$i]->id}}">{{$cat[$i]->name}}</option>
@endfor
@endfor
</select>


I want to get something like following image..
enter image description here

Answer

What you need is to make $catOfPost as an array that will contain only ids of all categories attached to a post. In this case your code will look like:

<select name="test[]">
      @for($i = 0; $i< count($cat); $i++)
          <option 
          @if(in_array($cat[$i]->id, $catOfPost) )
            class="test"
          @endif  
          value="{{$cat[$i]->id}}">{{$cat[$i]->name}}</option>
      @endfor
</select>

To create an array with ids only you should use the following code:

$catOfPostIds = [];
foreach($catOfPost as $item) {
    $catOfPostIds[] = $item->id;
}
Comments