Get Current Cart Details in Magento 2

Get Current Cart Details in Magento 2

In this article, we will show you the way to get cart details and cart items in Magento 2 by using the listed commands.

In Magento 2, to get the information of the cart items as a whole or individually such as subtotal, grand total, and billing & shipping address we use the Checkout Session.

Let’s Check out how to use the Checkout Session to Get Current Cart Details in Magento 2.

Get Cart Items using Dependency Injection:

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

    // get an array of all items that can be displayed directly
    $items = $this->checkoutSession->getQuote()->getAllVisibleItems();

    // get quote items array
    $items = $this->checkoutSession->getQuote()->getAllItems();

    foreach($items as $item) {
        echo 'ID: '.$item->getProductId().'<br />';
        echo 'Name: '.$item->getName().'<br />';
        echo 'Sku: '.$item->getSku().'<br />';
        echo 'Quantity: '.$item->getQty().'<br />';
        echo 'Price: '.$item->getPrice().'<br />';
        echo "<br />";
    }

    $subTotal = $this->checkoutSession->getQuote()->getSubtotal();
    $grandTotal = $this->checkoutSession->getQuote()->getGrandTotal();

    $billingAddress = $this->checkoutSession->getQuote()->getBillingAddress();
    echo '<pre>'; print_r($billingAddress->getData()); echo '</pre>';

    $shippingAddress = $this->checkoutSession->getQuote()->getShippingAddress();
    echo '<pre>'; print_r($shippingAddress->getData()); echo '</pre>';

}

Get Cart Items using Object Manager:

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Session');
    $grandTotal = $cart->getQuote()->getGrandTotal();
?>

NOTE: Magento\Checkout\Model\Cart is now deprecated.

That are all things you will use to retrieve the data of shopping cart items, subtotal, grand total, billing & shipping address in Magento 2.

I hope this helps! If you have any further questions, please don’t hesitate to reach out.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments