4

I have user and role two table data,I've fetch the data using eloquent and send to my view. Now, I want to populate user role checkbox dynamically. at this time which is I've written as hard code

Here,is my code.

@foreach($users as $user)
    <tr>
        <td>{{$user->name}}</td>
        <td>{{$user->email}}</td>

         @foreach($user->roles as $role)

        <td><input type="checkbox" name="" {{$user->hasRole('User') ? 'checked' : ''}}></td>
        <td><input type="checkbox" name="" {{$user->hasRole('Admin') ? 'checked' : ''}}></td>
        <td><input type="checkbox" name="" {{$user->hasRole('Author') ? 'checked' : ''}}></td>
         @endforeach
        <td></td>
    </tr>
    @endforeach

My Eloquent Query.

    $users=User::with('roles')->get();

    return view('admin',compact('users'));

User Model Relationship.

 public function roles()
{
    return $this->belongsToMany('App\Role');
}

1 Answer 1

2

In controller, you also need to load all the roles:

$users = User::with('roles')->get();
$roles = Role::get();
return view('admin', compact('users', 'roles'));

And in the view, do something like this:

@foreach($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->email }}</td>

        @foreach($roles as $role)
            <td><input type="checkbox" name="role[]" {{ $user->roles->contains($role) ? 'checked' : '' }}></td>
        @endforeach
        <td></td>
    </tr>
@endforeach

So, you need to iterate over all roles and not just over roles that user has.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.