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

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

6 days ago