Since it is a many-to-many
relationship so you are getting a collection in the $user
when you use following code:
$user = Auth::user()->roles;
So, you need to loop all the Role
models and have to check if($someUser->role == 'admin')
within the loop and in this case you may do it like this:
$roles = Auth::user()->roles;
$isAdmin = false;
$isAdmin = !$roles->filter(function($role) {
return $role->role == 'admin';
})->isEmpty();
if($isAdmin) {
// admin...
}
Also you may add a method in your User
model like this:
// User model
public function isAdmin()
{
$isAdmin = false;
$isAdmin = !$this->roles->filter(function($item) {
return $item->role == 'admin';
})->isEmpty();
return $isAdmin;
}
So you can use:
if(Auth::user()->isAdmin()) {
// admin...
}
Update: Check any role:
public function hasRole($role = null)
{
$hasRole = false;
$hasRole = !$this->roles->filter(function($item) {
return $item->role == $role;
})->isEmpty();
return $hasRole;
}
Now you can use:
if(Auth::user()->hasRole('encoder')) {
//...
}