X
    Categories: Knowledgebase

How to clear items in cart magento 1&2

Magento 1 :

The code for delete shopping cart items for logged in customer:

$cart = Mage::getSingleton('checkout/cart'); 
$quoteItems = Mage::getSingleton('checkout/session')
                  ->getQuote()
                  ->getItemsCollection();
 
foreach( $quoteItems as $item ){
    $cart->removeItem( $item->getId() );    
}
$cart->save();

The code for delete shopping cart items for all customers:

$quoteCollection = Mage::getModel('sales/quote')
			->getCollection()
			->addFieldToFilter('is_active', 1);
 
foreach ($quoteCollection as $item) {
	$item->delete();	
}

If you have a large number of customers quotes then deleting them by using loop might be time and resource consuming. You can clear/delete all customers cart items (all active sales quotes) by using the following SQL query:

DELETE FROM sales_flat_quote WHERE is_active = 1;

is_active = 0 means those quotes have been converted into orders, i.e. customer has placed order for those quotes.
is_active = 1 means quotes that have not been ordered, i.e. quotes present in the shopping cart of customers

Running this query will automatically delete related rows (quote items) from sales_flat_quote_item table through foreign key constraint.

Magento 2 :

To delete items from cart you need to follow these functions:

//instance of object manager 
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
//checkout session
$checkoutSession = $objectManager->get('MagentoCheckoutModelSession');
//returns all items in session
$allItems = $checkoutSession->getQuote()->getAllVisibleItems();
foreach ($allItems as $item) {
    //item id of particular item
    $itemId = $item->getItemId();
    //load particular item which you want to delete by his item id
    $quoteItem = $objectManager->create('MagentoQuoteModelQuoteItem')->load($itemId);
    //deletes the item
    $quoteItem->delete();
}

Thank for reading this post, Hope it helps.

Kien Wiliam: Magento Ecommerce Developer