Kevin Ilondo
Kevin Ilondo

Reputation: 35

Foreach loop only returns the latest result from a query in laravel

I want to loop through a collection and do a query for each item of this collection but the foreach loop only returns the latest result. How can I solve this problem?

foreach ($conversations as $conversation) {

    if ($conversation->id_participant1 !== Auth::user()->id) {

        $users = User::where(function ($query) use ($conversation) {
            $query->where('id', $conversation->id_participant1);
        })
            ->get();
    } else {
        $users = User::where(function ($query) use ($conversation) {
            $query->where('id', $conversation->id_participant2);
        })
            ->get();
    }
}

Upvotes: 0

Views: 620

Answers (1)

Armen
Armen

Reputation: 76

you are overwriting in every loop $user variable you can create empty array on the top of foreach, and push users to that variable

$users = []
foreach ($conversations as $conversation) {

if ($conversation->id_participant1 !== Auth::user()->id) {

    $users[] = User::where(function ($query) use ($conversation) {
        $query->where('id', $conversation->id_participant1);
    })
        ->get();
} else {
    $users[] = User::where(function ($query) use ($conversation) {
        $query->where('id', $conversation->id_participant2);
    })
        ->get();
    }
}

Upvotes: 6

Related Questions