Matt Pierce
Matt Pierce

Reputation: 805

Laravel Get Collection From Array of IDs

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

Answers (2)

Davor Minchorov
Davor Minchorov

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

ceejayoz
ceejayoz

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

Related Questions