Magento2 – How to Get All Items from Cart

cartcheckoutmagento2products

I have a custom module where I want to get all items from the cart and take a custom attribute(days_to_dispatch), but I don't know why I don't see that attribute and others(description, short_description, etc).
In the block Products.php:

protected $checkoutSession;
public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Helper\Data $helper,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Framework\App\ResourceConnection $resourceConnection,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    )
    {
        $this->_helper = $helper;
        $this->_productFactory = $productFactory;
        $this->_resourceConnection = $resourceConnection;
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
    }

public function getCartProducts(){
        $this->_checkoutSession->getQuote();
        if (!$this->hasData('quote')) {
            $this->setData('quote', $this->_checkoutSession->getQuote());
        }
        return $this->_getData('quote');
    }

And in my phtml file, I put

<?php
$quote = $block->getCartProducts();
foreach($quote->getAllVisibleItems() as $_item) {
    echo "<pre>"; var_dump($_item->debug());
}
?>

but I don't see that attribute.

Best Answer

To get Custom Attribute at cart item level, you need to define attribute in Vendor/Module/etc/catalog_attributes.xml.

refer below Example.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="quote_item">
        <attribute name="days_to_dispatch" />
    </group>
</config>

You can then write below code to get value.

$product = $item->getProduct()->getDaysToDispatch(); // where item is cart item

Related Topic