Jim Peeters Jim Peeters - 6 months ago 7
PHP Question

How to check matches between 2 arrays with foreach in laravel blade?

I have an array of tags from my database. I also have attached tags from a current item. I want to check wether tags are already attached or not. This seems to work but of course I get duplicate items in my select-field when there is originally more than 1 tag attached to the item. How can I avoid this ?

<select name="tags" multiple required>
@foreach ($tags as $name)
@foreach($item->tags as $itemtag)
@if($name == $itemtag->name)
<option value="{{$name}}" selected>{{$name}}</option>
@else
<option value="{{$name}}">{{$name}}</option>
@endif
@endforeach
@endforeach
</select>


$tags array :

{"9":"Acoustic","3":"Angry","6":"Autumn","10":"Banjo","13":"Bass","14":"Cheerful","12":"Chill","35":"Dirty","8":"Electric","22":"Epiphone","24":"ESP","19":"Fender","33":"Funk","16":"Funny","18":"Gibson","30":"Gretsch","32":"Groovy","1":"Happy","20":"Ibanez","23":"Jackson","31":"Les Paul","28":"Martin","15":"Mellow","21":"Paul Reed Smith","27":"Redwood","2":"Sad","29":"Schecter","17":"Sleepy","34":"Spanish","7":"Spring","4":"Summer","26":"Taylor","11":"Ukulele","5":"Winter","25":"Yamaha"}


$loop->tags array :

[{"id":1,"created_at":null,"updated_at":null,"name":"Happy","pivot":{"FK_loop_id":2,"FK_tag_id":1}},{"id":4,"created_at":null,"updated_at":null,"name":"Summer","pivot":{"FK_loop_id":2,"FK_tag_id":4}},{"id":14,"created_at":null,"updated_at":null,"name":"Cheerful","pivot":{"FK_loop_id":2,"FK_tag_id":14}},{"id":9,"created_at":null,"updated_at":null,"name":"Acoustic","pivot":{"FK_loop_id":2,"FK_tag_id":9}}]

Answer

This should work :

<select name="tags" multiple required>
@foreach ($tags as $name)
    @foreach($item->tags as $itemtag)
        @if($name == $itemtag->name)
            <option value="{{$name}}" selected>{{$name}}</option>
            <?php continue 2; ?>
        @endif
    @endforeach
    <option value="{{$name}}">{{$name}}</option>
@endforeach