Question

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

  • 1 -> admin
  • 2 -> encoder
  • 3 -> salesman
  • 4 -> tech

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.

Table Structure

users

  • id
  • email

roles

  • id
  • role

role_user

  • id
  • role_id
  • user_id

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
}
Was it helpful?

Solution 2

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')) {
    //...
}

OTHER TIPS

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"!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top