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

martinszeltins's avatar

Is there a way to do this query without selectRaw?

I have this query but I am using selectRaw and I'm wondering if it can be done without selectRaw but with ->sum() instead? But it doesn't group it if I use sum().

$contracts = Contracts::all();
$total_sums = Payments::selectRaw('contract_id, sum(paid) as paid_sum')
                        ->whereIn('contract_id', $contracts->pluck('id'))
                        ->groupBy('contract_id')
                        ->get();

The result

[
  {
    "contract_id": 157853,
    "paid_sum": "14.00"
  },
]
0 likes
1 reply
jlrdw's avatar

Bindings aren't needed there, and it's numeric, so there's nothing wrong with selectRaw.

A raw, from my experience is usually needed for a field using as. But I could be wrong.

What else have you tried.

Of course you could just write a regular query with db facade.

Please or to participate in this conversation.