0

I have two arrays of objects and I want to check if ids of elements of both are the same then select option in select box otherwise just display it. I tried like this:

 <select multiple class="form-control" name="category_id[]">
         @foreach($mysliwski as $mysl)
            @if(!$product->categories->isEmpty())
               @foreach($product->categories as $cat)
                  @if($mysl->id == $cat->id)
                      <option selected value="{{$mysl->id}}">{{$mysl->name}}</option>
                  @else
                      <option value="{{$mysl->id}}">{{$mysl->name}}</option>
                  @endif
               @endforeach
          @else
             <option value="{{$mysl->id}}">{{$mysl->name}}</option>
          @endif
          @endforeach
 </select> 

But it works only when one category is the same. When there are more my select option are duplicated. Here are my two arrays. Where I have bug?

Zobo
  • 283
  • 1
  • 3
  • 15
  • ugh - that template syntax is so ugly ( blade ) right? Makes me feel like you are suppressing all these errors ... lol – ArtisticPhoenix Jul 25 '15 at 07:31
  • first of logic of this sort is probably best done out side of the template, like in a model or controller. It's maybe to much for the template, you could build the array you want and then it would be easy as pi to put it on the page - ie the place for business logic is not in a template. – ArtisticPhoenix Jul 25 '15 at 07:34
  • But I want to have all categories in select box with selected categories that belong to product. – Zobo Jul 25 '15 at 07:35
  • 2
    Then make an array of all the items, then make one of all the items to check, deciding to check or not should be done elsewhere. And the checking be done on the page. What's this 'data' look like anyway. – ArtisticPhoenix Jul 25 '15 at 07:37

1 Answers1

0

You could achieve that like this

<select multiple class="form-control" name="category_id[]">
         @foreach($mysliwski as $mysl)
            @if(!$product->categories->isEmpty())
               {{-- */$selected='';/* --}}
               @foreach($product->categories as $cat)
                  @if($mysl->id == $cat->id)
                      {{-- */$selected='selected';/* --}}
                  @endif                                            
               @endforeach
               <option {{ $selected }} value="{{$mysl->id}}">{{$mysl->name}}</option>
          @else
             <option value="{{$mysl->id}}">{{$mysl->name}}</option>
          @endif
      @endforeach
 </select> 

Note: {{-- */$selected='';/* --}} is a tricky way of declaring a variable in a blade template. See https://stackoverflow.com/a/17176876/170539

Community
  • 1
  • 1
Scott Anderson
  • 1,363
  • 1
  • 10
  • 19