Skip to content
Advertisement

Laravel Lumen Collection – Group By With Sum and preserve the values

I’m working on Lumen and my collection has duplicate values, example:

JavaScript

I would like to sum the value property when the name is the same but preserve other values like (department and phone) and remove duplicates entity, example:

JavaScript

What’s the best way to do this?

Advertisement

Answer

This can be achieved using collection functions (https://laravel.com/docs/8.x/collections). In this example I solved it using (groupBy, map, flatten, slice, count and sum).

JavaScript

When calling print_r($data->toArray()); we get the following array as result:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement