This article shows how to get stock quantity (qty) of a product in Magento 2. We can also fetch other stock information like minimum quantity (min_qty), minimum sale quantity (min_sale_qty), maximum sale quantity (max_sale_qty), see if a product is in stock (is_in_stock), etc.
We will be using Magento 2’s Service Layer for this task. Use of Service Layer is highly encouraged by Magento.
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\CatalogInventory\Model\Stock\StockItemRepository class in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld 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);
}
}
?>
Now, we load the product by id and sku in template file.
$id = YOUR_PRODUCT_ID;
$productStock = $block->getStockItem(1225);
//print_r($productStock->getData());
echo $productStock->getQty(); echo '<br />';
echo $productStock->getMinQty(); echo '<br />';
echo $productStock->getMinSaleQty(); echo '<br />';
echo $productStock->getMaxSaleQty(); echo '<br />';
echo $productStock->getIsInStock(); echo '<br />';
Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$stockItem = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');
$id = 1; // YOUR PRODUCT ID
$productStock = $stockItem->get($id);
var_dump($productStock->getData());
Hope this helps. Thanks.