In this post I am going to explain How to Get Product Stock Information in Magento 2.
Use below methods to get product stock information in Magento 2 such as stock status, minimum stock quantity, minimum sale quantity, minimum quantity, etc.
Using below code snippet you can get product stock data by passing product id.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 | private $stockRegistry; public function __construct( \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry ) { $this->stockRegistry = $stockRegistry; } public function getStockInformation() { return $this->stockRegistry->getData(); } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 | // product Id $productId = 1; $StockData = $block->getStockInformation($productId); if ($stockData && count($stockData) > ) { echo $manageStock = $stockData['manage_stock']; echo $qty = $stockData['qty']; echo $minQty = $stockData['min_qty']; } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($_product->getId()); $stockData = $stockRegistry->getData(); if ($stockData && count($stockData) > ) { echo $manageStock = $stockData['manage_stock']; echo $qty = $stockData['qty']; echo $minQty = $stockData['min_qty']; } |
That’s it. Enjoy Magento 2!!
Check this Best Magento 2 Tutorial.
Leave a Reply