Using Eloquent relations would be so much easier;
$users = User::with('posts', 'friends')->get();
foreach ($users as $user) {
dump($user->posts);
dump($user->friends);
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
It's similar to the other post, but a different approach.
If I have 2 joins:
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->leftJoin('friends', 'users.id', '=', 'friends.user_id')
->get();
And I want to iterate by each unique user id, and display the list of his posts and friends, how can I do that?
foreach (unique user as $user) {
// print_r(all of this $user's posts)
// print_r(all of this $user's friends)
}
Please or to participate in this conversation.