Magento 2 get product stock detail
Magento 2 get product stock detail– We can get product stock information using \Magento\CatalogInventory\Model\Stock\StockItemRepository object. We can inject this object to class or object manager. Here in this article, we are going to explain both the methods.
Magento 2 get product stock detail | Availability Example
You can get the following product stock information –
- Quantity(Qty)
- Minimum Quantity(min_qty)
- Minimum Sale Quantity(min_sale_qty)
- Maximum Sale Quantity(max_sale_qty)
- Stock Availability(is_in_stock)
Method 1
Module name is – Tutorialsplane_HelloWorld, Inject object \Magento\CatalogInventory\Model\Stock\StockItemRepository in class constructor of block. Here is sample block-
<?php namespace Tutorialsplane\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 you can load product by id and get stock information in template file-
$productId = 120; $stock = $block->getStockItem($productId); $qty = $stock->getQty(); $minQty = $stock->getMinQty(); $minSaleQty = $stock->getMinSaleQty(); $maxSaleQty = $stock->getMaxSaleQty(); //checks product is in stock or not $isInStock = $stock->getIsInStock();
Method 2 Using Object Manager
You can use object manager to get stock information in Magento 2 simply as below-
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $appState = $objectManager->get('\Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $stockItem = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository'); $productId = 120; $stock = $stockItem->get($productId); $qty = $stock->getQty(); $minQty = $stock->getMinQty(); $minSaleQty = $stock->getMinSaleQty(); $maxSaleQty = $stock->getMaxSaleQty(); //checks product is in stock or not $isInStock = $stock->getIsInStock();
You can use any of the above method to get the product stock information in Magento 2. You can use the above method to check whether a product is in stock or out of stock.
Advertisements