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');
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With