Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

timgavin's avatar

Converting query to Eloquent

A site user can refer another site user.

The referred site user (user_id in the query) can do things on the site which will give the referring user (referred_by in the query) points, as a way of rewarding them for the referral.

I want to get the total number of reward points (total) from each column and display it.

The following query works, but I'm having a hard time converting it to Eloquent. Any suggestions?

select username, sum(total) as points_total
from referrals
join users on users.id = referrals.user_id
where referrals.referred_by = 3
group by referrals.user_id
0 likes
1 reply
timgavin's avatar
timgavin
OP
Best Answer
Level 11

Got it.

$query = \App\Referrals::selectRaw('username, SUM(total) AS points_total')
    ->leftJoin('users', 'users.id', '=', 'referrals.user_id')
    ->where('referrals.referred_by', 3)
    ->groupBy('user_id')
    ->get();

Please or to participate in this conversation.