Magento 2 – Get Cart Information After Customer Login

customerevent-observermagento2magento2.1.6

Customer has already Items in Cart. He is logout.

I'm using customer_login observer. It is correct?

How to get customers all cart information after his successfull login?

namespace Custom\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ObjectManager;

class CustomerLoginAfter implements ObserverInterface {

    protected $checkoutSession;
    protected $cart;

    public function __construct(\Magento\Checkout\Model\Session $checkoutSession, \Magento\Checkout\Model\Cart $cart) {
        $this->checkoutSession = $checkoutSession;
        $this->cart = $cart;
    }

    public function execute(Observer $observer) {

        $quoteItemsAll = $this->checkoutSession->getQuote()->getAllItems();
        echo count($quoteItemsAll);
        exit;
        return $this;
    }

}

It gives 0 count. While I already have 6 Items in Cart.

How to get customer's previous quote & it's items?

Best Answer

First, you should add Magento_Checkout as a depend module for your moule Custom_Module.

This depend tag use for as at customer_login event magento merge current quote(Quote which is created before login ) and already existing code(active quote which exists in customer account).

This depends make an <sequence> tag make sequence in execution of this two module ,First fire checkout module then your module means you will get merge quote object

    <sequence>
        <module name="Magento_Checkout"/>
    </sequence> 

Then at your observer ,you can get item qty by below code:

$this->checkoutSession->getQuote()->getItemsQty() * 1

And to get all visible items:

$quoteItemsAll = $this->checkoutSession->getQuote()->getAllVisibleItems();
Related Topic