In today’s tutorial, I am showing how to get the product stock quantity and information in Magento 2.
In this article, I will illustrate mainly two methods to get product stock information in Magento 2, and both methods are tested and confirmed it’s working.
#Method 1
This method will be using \Magento\CatalogInventory\Model\Stock\Item class to get the stock item in Magento 2
For the sake of example, I will use a helper class to get the stock details of a product.
class Data extends AbstractHelper
{
public function __construct(
....
\Magento\CatalogInventory\Model\Stock\Item $stockItem,
....
) {
$this->_stockItem = $stockItem;
}
public function getStockDetails($productId) {
$stockItemSingle = $this->_stockItem->load($productId, 'product_id');
print $stockItemSingle->getQty();
}
}
#Method 2
This method will be using \Magento\CatalogInventory\Api\StockStateInterface class to get the stock item in Magento 2
For the sake of example, I will use a helper class to get the stock details of a product.
class Data extends AbstractHelper
{
protected $_stockStateInterface;
public function __construct(
....
\Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
....
) {
$this->_stockStateInterface = $stockStateInterface;
}
public function getStockDetails($productId) {
print $this->_stockStateInterface->getStockQty($productId)
}
}
Hope this helps, and please don’t forget to share, so it might help others
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply