Skip to content
Advertisement

laravel avoid multiple Select’s Option in blade

simply in my controller i have this collections:

$category = Category::with('users')->find($id);
$users = User::with('roles')->get();

and in front end i try to check which users in $users is into $category->users, like with:

in Category model which that belong to User i have one or multiple stored users and i would like checked html option if each $category has user which that is into $user

<select class="form-control multiselect-filtering" multiple="multiple" name="users[]">
    @foreach ($category->users as $guser)
        @foreach ($users as $user)
            <option value="{{$guser->id}}"
                    @if ($guser->id == $user->id)
                       selected="selected"
                    @else
                       ''
                    @endif
                        >
            {{$user->username}}
            </option>
        @endforeach
    @endforeach
</select>

this code and compare works, but i have multiple <option> which they are maybe selected or not. how can i solve this issue?

Advertisement

Answer

You can loop over the collection which is in the $users variable, and use the contains method to check if the current user id in the loop is contained in the $category->users collection.

@foreach ($users as $user)
     <option value="{{$user->id}}"
           @if ( $category->users ->contains('id', $user->id))
                   selected="selected"
           @endif
      >
            {{$user->username}}
        </option>
@endforeach
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement