Can try with following code-
$userId = \App\User::where('your-table-colum-field')
->lists('id')->toArray();
$userDetails = \App\User::whereIn('id', $userId)
->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I currently have the following query where I grab all users that have a role of 1,2,3 in the database. I grab their first name and last name and id for the sole purpose of a select box. What I'm wanting to do is with the ids that I pass in the whereIn to also grab the role name so I can use it for creating option groups.
$options = \App\User::whereHas('roles', function ($query) {
$query->whereIn('id', [1, 2, 3]);
})->get()->map(function ($user) {
$user->name = $user->first_name . ' ' . $user->last_name;
return $user;
})->pluck('name', 'id');
Flip it on it's head.
Rather than trying to find Users, then map them to the Role, find the Role, then find the associated Users with each role.
$options = \App\Role::whereHas('users', function ($query) {
$query->whereIn('roles.id', [1, 2, 3]);
})->get()->map(function ($role) {
$users = $role->users->map(function($user) {
return sprintf('%s %s', $user->first_name, $user->last_name);
})->toArray();
return ['role' => $role->name, 'users' => $users];
})->keyBy('role')->map(function($user) {
return $user['users'];
});
This will give you an array which looks like;
Role A
- User 1
- User 2
Role B
- User 3
- User 4
You'd be able to plug that straight into the Form package and generate that markup you posted.
Please or to participate in this conversation.