Magento 2 Clear Cart programmatically – Sometimes we need to clear cart(Quote) programmatically in Magento, It is very simple to remove items from cart. Here in this tutorial we are going to explain how you can clear cart(quote) items programmatically.
Magento 2 Clear Cart programmatically | Remove Quote Items | All Items Example
First you need to get the items from the cart session then remove items one by one simply as below-
Remove All Items
The below exmple will remove all items.
Magento 2 Clear Cart programmatically Example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $allItems = $cart->getQuote()->getAllVisibleItems(); foreach ($allItems as $item) { $itemId = $item->getItemId(); $cart->removeItem($itemId)->save(); } |
So the above example can be used anywhere to remove items using code.
Remove Cart Item By Item Id
If you want to remove some specified item from cart you can remove it by Id. Here in a simple example to remove quote item by Id-
Magento 2 Clear Quote Item By Item Id Example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $itemId = 1011; $cart->removeItem($itemId)->save(); // item removed successfully |
Thus you can remove any item from cart/quote by item_id.
Tags
Magento 2 remove item from cart programmatically