Magento 2 Get Product Stock Quantity

If you want to use the stock related funtionalities like retrieving product stock quantity, you can use the following:

1) We need to include the following class into your custom class to access the Magento product inventory methods.

use Magento\CatalogInventory\Api\StockRegistryInterface;

2) Next we have to inject the StockRegistryInterface interface into your custom class constructor as dependancy injection as following :

protected $stockRegistry;

public function __construct(
StockRegistryInterface $stockRegistry
$this->stockRegistry = $stockRegistry;

3) Finally you just need to call the getProductStockQty() method to get product stock quantity by passing product id as parameter

public function getProductStockQty($productId) {
if(!empty($productId)) {
$stockItem = $this->stockRegistry->getStockItem($productId);
return $stockItem->getQty();
} else {
return null;

You can also use the following regular used public methods defined in the above interface class:

public function getStockItemBySku($productSku, $scopeId = null);
public function getStockStatus($productId, $scopeId = null);
public function getProductStockStatus($productId, $scopeId = null);
public function getProductStockStatusBySku($productSku, $scopeId = null);
public function updateStockItemBySku($productSku, \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem);

Hope this helps you guys!

Leave a Reply