Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Sum a Collection with multiple items

Tags:

laravel

I have a model SettlementEntries that has a relation to a sub table return $this->hasMany('App\Online', 'entry_id');

When trying to fetch one single Entry i'm able to sum my collection like in the example below.

$item = SettlementEntries::find($id);
$item->Online->sum('field'); // returns the correct sum

My problem starts when the $id is an array, so my result contains 2 SettlementEntries.

 $items = SettlementEntries::find($ids);
 $items->Online->sum('field'); <- returns zero

What is the correct way to retrieve those sums?

like image 416
DavidCandreva Avatar asked Oct 30 '25 01:10

DavidCandreva


1 Answers

Laravel's Collection makes this very easy, by using dot notation. Some examples here.

The simple way (dot notation):

$sum = $items->sum('Online.field');

More explicit (callback):

Or, if you want to be more explicit, e.g. using conditions/filters: provide a Closure:

$sum = $items->sum(function($item) {
  return $item->Online->sum('field');
});
like image 69
Jan Willem Avatar answered Oct 31 '25 21:10

Jan Willem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!