Blade - Go through two arrays

0

I have a function that collects the data of a user and also collects the rols that are in the system, the idea is to compare what is in the system with the user is assigned and check them with a checkbox

The method that collects the roles of a user is this

    public function editUser($id)
{
    $user = User::find($id);
    $rolesUser = $user->roles;
    $roles = Role::$roles;

    return view('users.edit', [
        'user' => $user,
        'rolesUser' => $rolesUser,
        'roles' => $roles
    ]);
}

Then from blade I have this foreach to go through the roles and show them

                            <div class="col-md-6 form-group">
                            <ul>
                                <label for="roles">@lang('messages.Roles') *</label>
                                @foreach ($rolesUser as $role)
                                    <li>
                                        <input type="checkbox" name="roles[]" value="{{ $role->id }}"> {{ $role->display_name }}
                                    </li>
                                @endforeach
                            </ul>
                        </div>

Now here I would miss that I do not know how to do, it is that I compare the array "roles" with "rolesUser" and leave checked the ones that match

    
asked by edica 08.08.2018 в 12:14
source

1 answer

0

What you could occupy here is the function in_array

What would give the following:

<div class="col-md-6 form-group">
<ul>
    <label for="roles">@lang('messages.Roles') *</label>
    @foreach ($rolesUser as $role)
        <li>
            <input type="checkbox" name="roles[]" value="{{ $role->id }}" @if(in_array($role->id, $roles)) checked="checked" @endif> {{ $role->display_name }}
        </li>
    @endforeach
</ul>

Although in this case, all checkboxes would be checked, since you are going through the roles that the user has assigned so that to show the entire list and only mark the user should be like this:

<div class="col-md-6 form-group">
<ul>
    <label for="roles">@lang('messages.Roles') *</label>
    @foreach ($roles as $role)
        <li>
            <input type="checkbox" name="roles[]" value="{{ $role->id }}" @if(in_array($role->id, $rolesUser)) checked="checked" @endif> {{ $role->display_name }}
        </li>
    @endforeach
</ul>

I hope I can help you.

    
answered by 08.08.2018 в 17:09