Get Product qty or stock information by Product Object is pretty easy in Magento 2.
We can simply get product qty from the product id and get the first product object. We can get product data from either by id or by SKU.
Please check below code snippet for getting product qty in Magento 2,
<?php namespace Rbj\Training\Block; class Product extends \Magento\Framework\View\Element\Template { protected $stockItemRepository; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository, array $data = [] ) { $this->stockItemRepository = $stockItemRepository; parent::__construct($context, $data); } public function getProductQty($id) { return $this->stockItemRepository->get($id); } }
Call template file by below code,
$product_id = 1; //product id $stock = $block->getProductQty($product_id); echo $stock->getQty(); // product qty echo $stock->getMinQty(); echo $stock->getMaxQty(); echo $stock->getIsInStock(); // is in stock return as boolean
You can fetch the Product Stock related data using the above Stock object.