Magento2 Stock – How to Get Product Quantity

magento2quantitystock

How to get stock quantity of each product in list.phtml in Magento 2 ?

Best Answer

Solution:1

Create Helper file Stock.php in your module

<?php
namespace {VendorName}\{ModuleName}\Helper;

class Stock extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var Magento\CatalogInventory\Api\StockStateInterface
     */
    protected $stockState;

    /**
     * Output constructor.
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\CatalogInventory\Api\StockStateInterface $stockState
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\CatalogInventory\Api\StockStateInterface $stockState
    ) {
        $this->stockState = $stockState;
        parent::__construct($context);
    }

    /**
     * Retrieve stock qty whether product
     *
     * @param int $productId
     * @param int $websiteId
     * @return float
     */
    public function getStockQty($productId, $websiteId = null)
    {
        return $this->stockState->getStockQty($productId, $websiteId);
    }
}

After add bellow code in your list.phtml file

$websiteId = 1;  // Current websiteId
$productId = 2; // $_product->getId()  Product Id
$_helperStock = $this->helper({VendorName}\{ModuleName}\Helper\Stock::class);
echo $_helperStock->getStockQty($productId, $websiteId);

Solution:2

Add bellow code in your list.phtml file

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
    echo $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
?>

OR

<?php
   $stockItem = $product->getExtensionAttributes()->getStockItem();
   print_r($stockItem->getQty()); 
?>
Related Topic