Reputation: 1755
This is how my collection looks like right now.
[{"id":"1","quantity":1},{"id":"2","quantity":1}]
What can I do to match the id
and change the quantity
to 2. This is for a shopping cart.
So in the end it would look like this if we found a item already in cart.
[{"id":"1","quantity":2},{"id":"2","quantity":1}]
Upvotes: 0
Views: 126
Reputation: 5186
You can use collection's transform
method. It iterates over the items in the collection, allowing you to change values.
Let's say your collection of objects is stored in $someCollection
. You could do this:
$someCollection->transform(function ($item, $key) use ($id) {
if ($item->id == $id) {
$item->quantity++;
}
return $item;
});
This will increase the quantity by one for the item with the id that you pass in $id
https://laravel.com/docs/5.2/collections#method-transform
Upvotes: 1