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?
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With