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

olehaugset's avatar

Summing a value and grouping by date on a eloquent collection

Hi.

I have a set of Eloquents that I got from my database. Lets say it looks something like this:

$mystuff = \App\Stuff::select(['n','dateDay','weight'])->get();

This gives me a collection of Stuff Eloquents.

However, I would like to reuse the $mystuff collection, without doing a second database query, to get the following two values: the sum of n, grouped by dateDay. There group by is important since there might be several of the Eloquents that have entries on the same dateDay.

I tried something like:

$num = $mystuff->sum('n')->groupBy('dateDay');

but this only gives me "Call to member function groupby() on integer".

I'm not sure if what I want to achieve is even possible here, but any tips would be much appreciated.

0 likes
3 replies
adamprickett's avatar
Level 6

You should group by first, then map to perform the aggregate function:

$num = $mystuff->groupBy('dateDay')->map(function ($row) {
    return $row->sum('n');
});
11 likes

Please or to participate in this conversation.