<?php
namespace Vendor\MagentoCustomer\Observer;
use Magento\Framework\Event\ObserverInterface;
class CustomerLogin implements ObserverInterface {
/**
* @param \Magento\Checkout\Model\Session
*/
protected $checkoutSession;
/**
* @var \Magento\Quote\Api\CartRepositoryInterface
*/
protected $quoteRepository;
public function __construct(
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository
) {
$this->checkoutSession = $checkoutSession;
$this->quoteRepository = $quoteRepository;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$customer = $observer->getEvent()->getCustomer();
$customerId = $customer->getId();
if($customerId){
//method 1
$quote= $this->checkoutSession->getQuote()->loadByCustomer($customerId);
$cartItems=$quote$cartItems1=$quote->getAllItems();
echo count(cartItemscartItems1);;echo '<br>';
//(OR) method 2
$customerQuote = $this->quoteRepository->getForCustomer($customerId);
$cartItems2=$customerQuote->getAllItems();
echo count($cartItems2);die;;echo '<br>';
//(OR) method 3
$quoteId = $this->checkoutSession->getQuote()->getId();
$quote = $this->checkoutSession->getQuote()->load($quoteId);
$cartItems3=$quote->getAllItems();
echo count($cartItems3);
}
}
}
$this->checkoutSession->getQuote()->loadByCustomer($customerId);
OR
$this->quoteRepository->getForCustomer($customerId);
these line willOR
$quote = $this->checkoutSession->getQuote()->load($quoteId);
All above methods can help you to fetch current customer cart items. Hope this helps.