How To

How to Programmatically Clear Shopping Cart in Magento 2

Since the era of e-commerce has started, developers are working hard to make CMS smarter and flexible with their coding capabilities. We developers are born to save time and efforts of end users by playing with codes and numbers. Also, day by day store owners become demanding to add new tons of functionality to improvise their store and stay ahead of the competition.

CHECK OUT: Magento 2 Save Cart Pro Extension for your store.

Recently while working on one of customers store, we came across the requirement of clearing shopping cart programmatically. Well, it is possible to clear the cart using three different ways which are mentioned below. Working with Magento several times you came across such a situation that’s why we thought of creating an article on Magecomp blog.

1. First method :
Create “Clearcart.php” file using following code at below location inside your custom extension folder.
app\code\vendor\extension\Controller\Index\Clearcart.php

namespace Vendor\Extension\Controller\Index;
use Magento\Checkout\Model\Cart;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\App\Action\Action;
class Clearcart extends Action
{
 protected  $_modelCart;
 protected $ checkoutSession;
 public function __construct(CheckoutSession $checkoutSession,Cart $modelCart)
        {
         $this->checkoutSession = $checkoutSession;
         $this->_modelCart = $modelCart;
        }
 public function execute()
        {
  $cart = $this->_modelCart;
  $quoteItems = $this->checkoutSession->getQuote()->getItemsCollection();
  foreach($quoteItems as $item)
  {
   $cart->removeItem($item->getId())->save(); 
  }
 }
}

2. Second Method :
In this method, we can get the current cart using model cart object and then simply truncate it.

namespace Vendor\Extension\Controller\Index;
class Clearcart extends Action
{
 public function execute()
 {
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
  $cartObject = $objectManager->create('Magento\Checkout\Model\Cart')->truncate(); 
   $cartObject->saveQuote();
 }
}

3. Third Method :
In this last method, we can delete item from cart Modal using below code.

namespace Vendor\Extension\Controller\Index;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Quote\Model\Quote\Item
 
class Clearcart extends Action
{
 protected  $modelCartItem;
 protected $checkoutSession;

 public function __construct(CheckoutSession $checkoutSession,Item $modelCartItem)
        {
         $this->checkoutSession = $checkoutSession;
                $this->_ modelCartItem = $modelCartItem;
        }

 public function execute()
 {
      $checkoutSession = $this->getCheckoutSession();
  $allItems = $checkoutSession->getQuote()->getAllVisibleItems();
  foreach ($allItems as $item) 
  {
       $cartItemId = $item->getItemId();
          $itemObj=$this->getItemModel()->load($cartItemId);
          $itemObj->delete();
  }
   }
}

From give three methods, you can pick any one according to your need and choice.
Lastly, Comment down below if you face an issue while using this code.
Happy Cart Cleaning!

Click to rate this post!
[Total: 32 Average: 3.8]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

  • Hi Dhiren,

    I have used your 3rd step cart cleared successfully. But in minicart shows the count as it before clearing the cart. Is any solution for this ?

    • You need to implement the sections.xml into your custom module and implement the section update after your above method calls. So it will update the section after your code is executed.

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

7 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago