Search code examples
laraveleloquentlaravel-10

How to get the sum in array of objects in Laravel eloquent


I have this Array of objects where I wanna sum up the quantity having the same barcode. Am using Laravel if you can give me a eloquent solution that will be great.

[
  {
    "id": 1,
    "barcode": "555",
    "description": "pencil",
    "quantity": "3",
  },
  {
    "id": 2,
    "barcode": "555",
    "description": "pencil",
    "quantity": "1",
  },
  {
    "id": 3,
    "barcode": "123",
    "description": "paper",
    "quantity": "1",
  },
  {
    "id": 4,
    "barcode": "123",
    "description": "paper",
    "quantity": "8",
  },

]

desired output

[
  {
    "id": 1,
    "barcode": "555",
    "description": "pencil",
    "qty": "4",
  },
  {
    "id": 2,
    "barcode": "123",
    "description": "pencil",
    "qty": "9",
  }
]

thanks


Solution

  • You can use the collection's groupBy and map (or flatMap) methods.

    $collection
        ->groupBy('barcode')
        ->map(fn ($group, $key) => [
            'id' => $group->first()['id'],
            'barcode' => $group->first()['barcode'],
            'description' => $group->first()['description'],
            'qty' => $group->sum('qty'),
        ])
        ->values();