Reputation: 805
I have an array of User IDs that I'm trying to get a collection of. I have been using the following foreach loop, but I realize that for each loop it makes, it overrides the previous data.
$users = DB::table('user_tags')->where('tag_name', $tag)->whereNotNull('user_id')->lists('user_id');
$users = array_unique($users);
foreach ($users as $key => $value)
{
$users = User::where('id', $value)->get();
}
How can this return a collection with all users in that original array?
Thanks!
Upvotes: 2
Views: 4626
Reputation: 2076
Is the relationship between users and tags many to many? If so, try the following query:
User::whereHas('tags', function($query) use ($tag) {
$query->where('tag', $tag);
})->pluck('id');
Upvotes: 0
Reputation: 180137
There's an easier way..
$ids = DB::table('user_tags')->where('tag_name', $tag)->whereNotNull('user_id')->lists('user_id');
$users = User::whereIn('id', $ids)->get();
Upvotes: 13