Get shopping cart details in Magento2

Jimmery picture Jimmery · Apr 22, 2016 · Viewed 26.1k times · Source

I know in Magento 1 you can get the shopping cart details on any page with:

$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
    $productId = $item->getProduct()->getId();
    $productPrice = $item->getProduct()->getPrice();
}

How do I do the same thing in Magento 2?

Answer

user2617403 picture user2617403 · Jun 15, 2016
protected $_checkoutSession;

public function __construct (
    \Magento\Checkout\Model\Session $_checkoutSession
    ) {
    $this->_checkoutSession = $_checkoutSession;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
  $cartData = $this->_checkoutSession->getQuote()->getAllVisibleItems();
  $cartDataCount = count( $cartData );
}

you can get the quote data in observer