Get product stock information in Magento 2

If you want to get stock data from a product without creating a new extension here what you need to do:

<?php
$productId = XXX;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$productStockObj = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($productId); ?>

With the $productStockObj you can get stock information, namely:

echo $_productStock->getQty();
echo $_productStock->getMinQty();
echo $_productStock->getMinSaleQty();
echo $_productStock->getMaxSaleQty();
echo $_productStock->getIsInStock();

To turn this into a module just inject the object of \Magento\CatalogInventory\Model\Stock\StockItemRepository class in the constructor of the module’s block class.

Here is a skeleton of that

app/code/WebGuru/StockInfo/Block/StockData.php

<?php
namespace WebGuru\StockInfo\Block;
class StockData extends \Magento\Framework\View\Element\Template
{    
    protected $_stockItemRepository;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
        array $data = []
    )
    {
        $this->_stockItemRepository = $stockItemRepository;
        parent::__construct($context, $data);
    }
    
    public function getStockItem($productId)
    {
        return $this->_stockItemRepository->get($productId);
    }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *