I don´t want to remove the duplicate values, I want to get the articles_id duplicates and sum their quantity values, for example, this is my collection:
Collection {#306 ▼
#items: array:3 [▼
0 => CartLine {#294 ▼
+quantity: 2
+article_id: 1728
+article_name: "TAZA CERAMICA"
}
1 => CartLine {#296 ▼
+parent_line_id: null
+quantity: 1
+article_id: 1728
+article_name: "TAZA CERAMICA"
}
2 => CartLine {#298 ▼
+quantity: 1
+article_id: 1378
+article_name: "JARRA CERVEZA ALEMANA"
}
]
}
And I want get this result:
Collection {#306 ▼
#items: array:3 [▼
0 => CartLine {#294 ▼
+quantity: 3 //sum total quantity of the duplicates elements with same article_id
+article_id: 1728
+article_name: "TAZA CERAMICA"
}
1 => CartLine {#296 ▼
+parent_line_id: null
+quantity: 3
+article_id: 1728
+article_name: "TAZA CERAMICA"
}
2 => CartLine {#298 ▼
+quantity: 1
+article_id: 1378
+article_name: "JARRA CERVEZA ALEMANA"
}
]
}
I want sum the quantities of the duplicate elements and set the quantity property with the sum in these elements.
You could try something like:
$collection->groupBy('article_id')->flatMap(function ($items) {
$quantity = $items->sum('quantity');
return $items->map(function ($item) use ($quantity) {
$item->quantity = $quantity;
return $item;
});
});
Obviously, change $collection
to be whatever you've called the variable that holds your collection.
Hope this helps!