I believe, your issue can be solved by Laravel Query Scope.
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.
You should group by first, then map to perform the aggregate function:
$num = $mystuff->groupBy('dateDay')->map(function ($row) {
return $row->sum('n');
});
Please or to participate in this conversation.