Magento 2: Rest API update multiple cart Items
-
14-04-2021 - |
Question
I need to update multiple cart items quantity in Rest API.
Default Magento only have update single cart item.
Single cart update Item endpoint:
/V1/carts/mine/items/:itemId
I have tried with custom endpoint but not get update multiple items.
Multiple item custom endpoint:
localhost/magento2/rest/V1/custom/carts/mine/update/items?cartItem[0][item_id]=85411&cartItem[0][qty]=2&cartItem[0][quote_id]=25645&cartItem[1][item_id]=85412&cartItem[1][qty]=1&cartItem[1][quote_id]=25645
Params:
cartItem[0][item_id] 85411
cartItem[0][qty] 2
cartItem[0][quote_id] 25645
cartItem[1][item_id] 85412
cartItem[1][qty] 1
cartItem[1][quote_id] 25645
Method: PUT
Let me know if any have idea about to update multiple cart items in rest API.
Any help would be appreciated. Thanks.
Solution
call the items in the loop and load quote object and set quantity or another field.
sample code
public function updateItems($cartId, $cartItem)
{
$result = $this->dataObjectFactory->create();
$quote = $this->quoteRepository->getActive($cartId);
foreach ($cartItem as $itemValue) {
$item = $this->quoteItemFactory->create()->load($itemValue['item_id']);
$item = $quote->getItemById($itemValue['item_id']);
$item->setQty($itemValue['qty']);
$quoteItems[] = $item;
}
$quote->setItems($quoteItems);
$this->quoteRepository->save($quote);
$quote->collectTotals();
$quote->getLastAddedItem();}
Please let me know if this is helpful.