Ayşe Taş
Ayşe Taş

Reputation: 79

Duplicate select2 item in the foreach loop

Hello everyone, I'm returning the data with foreach from the dishes table in foods. I bring the selected ids as selected, but this time it is copied until the selected one.

 <select class="form-control select2 "  name="lunch" multiple="" data-select2-id="lunch{{$item->id}}"  aria-hidden="true">
<optgroup label="Öğle Yemeği" >
    @foreach ($foods as $food)
        @foreach ($item->dinner as $lunch)
            @if ($lunch != $food->id)
                @continue
            @else
                <option value="{{$food->id}}"  selected >{{$food->name}}</option>
                @break
            @endif
        @endforeach
        <option value="{{$food->id}}">{{$food->name}}</option>
    @endforeach
</optgroup></select>

My output of code like this: http://prntscr.com/110203m How can i fix that?

Upvotes: 0

Views: 1035

Answers (1)

Kongulov
Kongulov

Reputation: 1161

Your code repeats 2 times

<option value="{{$food->id}}"  selected >{{$food->name}}</option>

Try using this code

<select class="form-control select2" name="lunch" multiple="" data-select2-id="lunch{{$item->id}}" aria-hidden="true">
    <optgroup label="Öğle Yemeği">
        @foreach ($foods as $food)
            <option value="{{$food->id}}" @if(in_array($food->id, $item->dinner)) selected @endif>{{$food->name}}</option>
        @endforeach
    </optgroup>
</select>

Still "continue" can be used like this

@continue($lunch != $food->id)

Upvotes: 1

Related Questions