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
What is 4 supposed to represent?
User::whereIn(4 <-
@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 yes but i want check specific role not all roles
@karimali1337 yeah that's what my example should do. It does not work?
@Sinnbeck so i replay the 'id' with the role id i wanna check am i understanding right ?
Maybe the confusion for me is ->role_ids which you say is user ids? Is that the case?
@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
@karimali1337 ok so id 1 we do
$Users= User::whereRelation('roles', 'id', 1)->whereNotNull('email')->get();
@Sinnbeck roles_id is a function in users model to get all user roles
public function getRoleIdsAttribute()
{
return $this->roles->pluck('id')->toArray();
}
@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();
@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.
@karimali1337 happy to help. Hope it makes sense and that you learn a little
Is this what you want?
$Users= User::whereIn('id', $usersIds)->whereNotNull('email')->get();
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 sign in or create an account to participate in this conversation.