Farshad
Farshad

Reputation: 2000

how to sum a collection after groupBy laravel

i have a collection named detailed as below :

Collection {#1421 ▼
  #items: array:2 [▼
    3943 => Collection {#1419 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#923 ▶}
        1 => RoomPricingHistory {#1042 ▶}
      ]
    }
    3944 => Collection {#1420 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#1153 ▶}
        1 => RoomPricingHistory {#1264 ▶}
      ]
    }
  ]
}

now i want to get the sum of RoomPricingHistory for 3943 item and 3944 ofc it can be more of 2 item so i want to get the sum of each collection how can i achieve that ??

Upvotes: 0

Views: 3468

Answers (1)

lagbox
lagbox

Reputation: 50491

The Collection sum method can take a callback so you can define what is going to be calculated. In this case you can call sum on the main collection and in the callback which will give you access to the internal collections, also call sum.

$detailed->sum(function ($group) {
    return $group->sum('sales_price');
});

Laravel 6.x Docs - Collections - Available Methods - sum

Since that isn't what you are looking for, you can use something like mapWithKeys to go through the collection and call sum for the groups to get the sum for each group:

$sums = $detailed->mapWithKeys(function ($group, $key) {
    return [$key => $group->sum('sales_price')];
});

Laravel 6.x Docs - Collections - Available Methods - mapWithKeys

Upvotes: 3

Related Questions