Two nested foreach duplicate options - select tag

Published 6 months ago by carincon93

I need to select the options with user roles

<select class="form-control" name="role_user">
// foreach - all roles
    @foreach ($roles as $role)
// foreach - roles user
        @foreach($user->roles as $userRole)
        <option value="{{ $role->id }}" {{$role->id == $userRole->id ? 'selected' : ''}} >{{ $role->name }}</option>
        @endforeach

    @endforeach
</select>

The previous code shows the following duplicate options:

student
student
admin
admin
Best Answer (As Selected By carincon93)
Snapey

you need one loop going over all possible roles, and then inside the loop use contains to see if the user has the role mentioned

Sergiu17

Could you do something like this?

<select>
@foreach ( $user->roles as $role)
    <option>{{ $role->name }}</option>
@endforeach 
</select?
carincon93

@Sergiu17 your code only show the roles assigned to user, I need to show all roles selecting the assigned to user

Snapey
Snapey
6 months ago (1,043,395 XP)

you need one loop going over all possible roles, and then inside the loop use contains to see if the user has the role mentioned

Please sign in or create an account to participate in this conversation.