I want to create a list of users with their specific role(or roles if multiple roles given)
In my UserController
use DB;
use Auth;
use Storage;
use App\Role;
use App\HasRoles;
use App\User;
use App\Profile;
$users = User::with('roles')->where('name', 'admin')->get();
return view('dashboard.users.index', compact('users'));
but I am having this error
if I dd($users);
I can see that the roles are there
How can I solve the issue? thanks!
EDIT: user model
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, HasRoles;
protected $fillable = [
'name', 'email', 'phone_number', 'avatar', 'password', 'verification_code'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
'phone_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne('App\Profile', 'user_id','id');
}
public function mailingAdd()
{
return $this->hasOne('App\MailingAddress', 'user_id','id');
}
user/index.php
@foreach($users->role as $item)
<tr>
<td>{{ $loop->iteration }}</td>
<td><a href="{{ url('/dashboard/users', $item->id) }}">{{ $item->name }}</a></td>
<td>{{ $item->email }}</td>
<td>{{ $item->role()->name }}</td>
<td>{{ $item->phone_number==null ? 'None' : $item->phone_number }}</td>
<td>
@if($item->phone_verfied_at==null)
<span class="badge badge-danger">not yet verified</span>
@else
<span class="badge badge-success">verified</span>
@endif
</td>
</tr>
@endforeach
Changing @foreach($users->role as $item)
into @foreach($user->roles as $item)
gives me "Property [roles] does not exist on this collection instance"
USER TABLE MIGRATION
ROLES AND PERMISSION TABLE MIGRATION
ANSWER
base from Simon Morris's answer.
@foreach($users as $user)
{{ $user->name }}
@foreach ($user->roles as $role)
{{ $role->name }}
@endforeach
@endforeach
I removed the relationship I added base from some of my suggestions here. and implement the answer I pasted above.
That code display the user list with their specific user role or roles if the user given multiple roles.
thanks guys for answering! cheers!