Home > Software design >  Laravel Sum on collection with duplicates data
Laravel Sum on collection with duplicates data

Time:10-29

I have an object that consists of multiple data as controlNumber each controlNumber has shipment.qty what I want is to total the qty of each same controlNumber and display one controlNumber with total qty.

collection is below

"collection": [
        {
            "id": 983,
            "controlNumber": 4498818,
            "ItemNumber": "PS2W12077",
            "shipment": {
                "id": 27,
                "Item": "PS2W12077",
                "ColorCode": "GRPFR",
                "qty": 1638
            }
        },
        {
            "id": 982,
            "controlNumber": 4498818,
            "ItemNumber": "PS2W12077",
            "shipment": {
                "id": 27,
                "Item": "PS2W12077",
                "ColorCode": "GRPFR",
                "qty": 1638
            }
        },
       {
            "id": 936,
            "controlNumber": 4498815,
            "ItemNumber": "PS2T01096",
            "shipment": {
                "id": 11,
                "Item": "PS2T01096",
                "ColorCode": "MALDI",
                "qty": 1212
            }
        },
 ]

controlNumber 4498818 has two shipment data with two qty what I want is to show one controlNumber with total qty of 3276

what I have retired is return total qty of all controlNumber

 $result = $collection->pipe(function ($collection) {
            return collect([
                'shipment_qty' => $collection->sum('shipment.qty'),

            ]);
        });

CodePudding user response:

you can use unique collection method to get only unique item based on control number value:

 $uniqueCollection=$collection->unique('controlNumber');

 $result=$collection2->sum(function ($item){
           return $item->shipment->qty;
       });

CodePudding user response:

With this you get a collection where key is controlNumber and value is sum of shipment->qty.

$collection->mapToGroups(function ($item) {
   return [$item->controlNumber => $item->shipment->qty];
})->map->sum();
  • Related