0
votes

I need help with querying the result of relation between models. Two models are defined, User and Role model.

User:

public function roles()
{
    return $this->belongsToMany('App\Role', 'role_users');
}

public function hasAccess(array $permissions) : bool
{
    foreach ($this->roles as $role) {
        if ($role->hasAccess($permissions)) {
            return true;
        }
    }

    return false;
}

public function inRole(string $slug)
{
    return $this->roles()->where('slug', $slug)->count() == 1;
}

Role:

public function users()
{
    return $this->hasMany('App\User', 'role_users');
}

public function hasAccess(array $permissions) : bool
{
    foreach ($permissions as $permission) {
        if ($this->hasPermission($permission)) {
            return true;
        }
    }

    return false;
}

private function hasPermission(string $permission) : bool
{
    return $this->permissions[$permission] ?? false;
}

Also, a pivot table called role_users is defined. In the roles database several roles are pre-defined by seeding (Admin, Editor, Author).

I want to query the users by its roles, for example,

$editors = App\User::roles(2)->orderBy('name', 'asc')->get()

where in roles database the id of editor is 2. I got the error

PHP Deprecated:  Non-static method App/User::roles()

How to solve this? Note: I'm using Laravel 5.6 and new to Laravel and framework. I tried to refer to docs but it confused me.

Thanks in advance.

2
So - you want to get the users that have the role with the id 2?DevK
Yes, exactly. Because I want to filter the users by its roles.Azwan Abdullah

2 Answers

1
votes

You have to use whereHas(..):

$editors = \App\User::whereHas('roles', function ($q) {
    $q->where('id', 2);
})->orderBy('name', 'asc')->get()
0
votes

@devk is correct but here you have another way to get the data of user by role.

\App\Role::where('id', 2)->with('users')->get();