Antonio Morales Antonio Morales - 2 days ago 5
PHP Question

Use Laravel Collection to get duplicate values

I don´t remove this duplicate values, I want get the articles_id duplicates and sum hers quantities values, por 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 this duplicate elements and set the quantity property with the sum only in this elements.

Answer

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!

Comments