Magento2
How to get Product Stock/Quantity Magento 2

In this blog we learn how to get stock(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.

Here is a block class of my custom module (Mtutorials_HelloWorld). I have injected object of \Magento\CatalogInventory\Model\Stock\StockItemRepository class in the constructor of my module’s block class.

app/code/Mtutorials/HelloWorld/Block/HelloWorld.php


Now, we load the product in template file and call a stock function, Given as below.

$productId = 123; // PRODUCT ID FOR LOAD PRODUCT STOCK
$productStock = $block->getStockItem($productId);
//var_dump($productStock->getData());
echo $productStock->getQty(); echo '
';
echo $productStock->getMinQty(); echo '
';
echo $productStock->getMinSaleQty(); echo '
';
echo $productStock->getMaxSaleQty(); echo '
';
echo $productStock->getIsInStock(); echo '
';

Load data Using Object Manager

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');

$stockObj = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$productId = 1; // YOUR PRODUCT ID

$stockitem = $stockObj->getStockItem($productId);
var_dump($stockitem);

NOTE : If you load data using Object Manager, Its increase the processing time.

Hope this will helps you!