Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anand_aks's avatar

Get All Users With A Particular Permission

I have table Client_users, Roles, and Permission along with pivot table client_user_role, permission_role.

How can I get all the users which have particular permission?

 $permission = Permission::find(1);
 $user = $permission->roles->users;

//Permission.php
public function roles(){
        
        return $this->belongsToMany(Role::class)->where('company_code',Auth::user()->company_code)->take(1);
        
    }

//Roles.php
 public function users()
    {
        return $this->belongsToMany(Client_user::class);
    }


But giving error

	Property [users] does not exist on this collection instance.

0 likes
2 replies
automica's avatar

@anand_aks your roles relationship returns a collection.

You'll need to loop through $permission->roles as $role and get $users = $role->user;

Alternatively you can define a relationship between Permission and User using hasManyThrough

From the docs https://laravel.com/docs/8.x/eloquent-relationships#has-many-through-key-conventions

class Project extends Model
{
    public function deployments()
    {
        return $this->hasManyThrough(
            Deployment::class,
            Environment::class,
            'project_id', // Foreign key on the environments table...
            'environment_id', // Foreign key on the deployments table...
            'id', // Local key on the projects table...
            'id' // Local key on the environments table...
        );
    }
}

adjust accordingly to your case

1 like
SilenceBringer's avatar

@anand_aks assuming you have appropriate relationships

Example with searching by name. Can replace with id

Client_user::whereHas('permissions', function ($query) use ($permissionName) {
    $query->where('name', $permissionName);
}
    ->orWhereHas('roles.permissions', function ($query) use ($permissionName) {
        $query->where('name', $permissionName);
    })
    ->get();
1 like

Please or to participate in this conversation.