Reputation: 2655
I have the following database structure a users & roles table joined using a pivot table:
The users table contains all the info such as email and password, while the roles table defines the different roles :
roles table
Now the roles are defined many-to-many because, there are some encoders that are assigned also as an admin. Others may have an salesman+admin role, or even encoder+salesman. Basically it multiple roles can be assigned to someone.
users
roles
role_user
I know that if I do
$user = User::find(1)->email;
return $user;
the result would display the email of the user with ID 1.
I was trying to do $user = Auth::user()->roles;
so that it will get the role of the currently authenticated user.
But doing so returns a JSON which displays all the roles the user is assigned to.
I was hoping to use this in a filter, to do something like this
$user=Auth::user()->roles;
if($user == 'admin')
{
//do something
}
else
{
//you are not an admin
}
if($user == 'encoder')
{
//do something
}
else
{
//you are not an encoder
}
Upvotes: 3
Views: 3615
Reputation: 133
Just a small fix for the code at the bottom:
public function hasRole($role = null) {
$hasRole = false;
$hasRole = !$this->roles->filter(function($item) use ($role) {
return $item->name == $role;
})->isEmpty();
return $hasRole;
}
@lozadaOmr: You have to add "use"!
Upvotes: 4
Reputation: 146191
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')) {
//...
}
Upvotes: 3