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

karimali1337's avatar

Laravel Query Error

i've 3 tables, User/Roles/role_user for multi roles user

when i'm trying to access the roles function to get all users in blade i use in_array and its okay but i'm trying to get it in controller with whereIn but there's mistake in query so any hints.

        $usersIds = auth()->user()->role_ids;
         $Users= User::whereIn(4, $usersIds)->whereNotNull('email')->get();

error

SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name '4'.
select * from [qps].[users] where [4] in (1, 3) and [email] is not null
0 likes
16 replies
Sinnbeck's avatar

What is 4 supposed to represent?

User::whereIn(4 <-
Sinnbeck's avatar

@karimali1337 so you want to query the pivot table? Is the relationship set up?

$roleIds = auth()->user()->role_ids;
         $Users= User::whereRelationIn('roles', 'id', $roleIds)->whereNotNull('email')->get();
Sinnbeck's avatar

Maybe the confusion for me is ->role_ids which you say is user ids? Is that the case?

karimali1337's avatar

@Sinnbeck let me simplify it.

lets say admin id in roles table =1

so i want to get the users with role admin

so in your example its general,i wanna put specific id to get the users from

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@karimali1337 ok so id 1 we do

$Users= User::whereRelation('roles', 'id', 1)->whereNotNull('email')->get(); 
karimali1337's avatar

@Sinnbeck roles_id is a function in users model to get all user roles

    public function getRoleIdsAttribute()
    {
        return $this->roles->pluck('id')->toArray();
    }

Sinnbeck's avatar

@karimali1337 ok so all users that has those roles?

$Users= User::whereHas('roles', function ($query) {
    $query->whereIn('id', auth()->user()->role_ids);
})->whereNotNull('email')->get(); 
karimali1337's avatar

@Sinnbeck That's it,Thank you.

As a junior i really put my hat off for you,

Every time i've a question you help and follow with me i really pleased to have people like you in this community.

Sinnbeck's avatar

Is this what you want?

$Users= User::whereIn('id', $usersIds)->whereNotNull('email')->get(); 
karimali1337's avatar

4= admin

in_array(4, auth()->user()->role_ids) this is the statement i use in blade to check if the user has role admin in table role_user

Please or to participate in this conversation.