1

Correct me if I'm wrong, but completely removing the cart content on customer log-out is not native to Magento 2 is it?

I read about the "Persistent cart" but it seems to work only for removing the cart content on logout but when the user logs back in, they get their cart content back.

I try to achieve the following scenario:

  1. Customer logs in to the website.
  2. Adds a product to cart.
  3. Logs out of the website.
    • Cart is empty (Persistent cart feature can do that)
  4. Customer logs back in to the website.
    • Cart is still empty (Not sure if this can be achieved using native functionality)

If this can be done using Native features of Magento 2 that would be great. If not, has anybody done that before? Any guidance will be appreciated.

1 Answer 1

0

I had the same problem and found a solution. I used Magento 2.2.

Basically you just have to listen for the customer_logout event and when it occures, clear the cart contents. The listening is done via an observer.

  1. Create a custom module if you havn't already
  2. In the module, create the file /etc/frontend/events.xml if it is not already present
  3. The events.xml should look like this:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

 <!-- Your other observers, if any -->

 <!-- Copy from here -->
 <event name="customer_logout"> <!-- use one of the events above -->
     <observer name="[Vendor]_[Name]" instance="[Vendor]\[Name]\Observer\Logout" />
 </event>
 <!-- to here -->
</config>
  1. Set your modules's [Vendor] and [Name] accordingly
  2. In the module, create the file /Observer/Logout.php
  3. The content of the Logout observer class should look like this:
<?php

namespace [Vendor]\[Name]\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Cart;

class Logout implements ObserverInterface
{
  protected  $cart;

  public function __construct(Cart $modelCart) {
      $this->cart = $modelCart;
  }

  public function execute(\Magento\Framework\Event\Observer $observer)
  {
      foreach($this->cart->getItems() as $item)
      {
          $this->cart->removeItem($item->getId());
      }
      $this->cart->save();
      $this->cart->saveQuote();  // I added both 'save' lines to make sure everything is persisted
      return $this;
  }
}

  1. Make sure to enter [Vendor] and [Name] accordingly to your module and events.xml
  2. Run php bin/magento setup:di:compile to set the observer active

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.