VishalPandita
VishalPandita

Reputation: 700

Magento 2: Get Product Stock Quantity and Other Stock Information

Magento 2: Get Product Stock Quantity and Other Stock Information

How to get the product stock quantity and information in magento 2

Upvotes: 4

Views: 40817

Answers (6)

Milan Chandro
Milan Chandro

Reputation: 2483

If you have the product object and do not want to use the other classes, You can try in the following way.

// For phtml file
$prodObj = $_product->load($_product->getId()); // $_product object in list.phtml
$stockItem = $prodObj->getExtensionAttributes()->getStockItem();
$stockQty = $stockItem->getQty(); // $stockItemData = $stockItem->getData();

// For php class file
$stockItem = $prodObj->getExtensionAttributes()->getStockItem();
$stockQty = $stockItem->getQty(); // $stockItemData = $stockItem->getData();

Upvotes: 2

Priyesh Doshi
Priyesh Doshi

Reputation: 380

Credits: https://github.com/magento/magento2/issues/7057#issuecomment-256052729

Actually \Magento\CatalogInventory\Api\Data\StockStatusInterface should answer to all your questions.

Long story short: Magento has StockItem entity which represents amount (Qty) of specific product (productId) on a concrete stock (stockId). StockItemInterface should be used when you would like to "write" data into the data storage (like update amount of products to sync up Magento with your ERP system or to make deduction of stock during the checkout process).

StockStatusInterface is opposite to it. It should be used to "read" data for representation (on front-end). Consider StockStatus as an index which contains aggregated stock data for each specific product.

So, if you would like to get product stock status (in stock, out of stock) by product_id. You need using StockStatusRepositoryInterface::getList(StockStatusCriteriaInterface $searchCriteria); get StockStatus entity for specified product

/** @var \Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory $stockStatusCriteriaFactory **/
        $criteria = $stockStatusCriteriaFactory->create();
        $criteria->setProductsFilter($productId);
        /** @var \Magento\CatalogInventory\Api\Data\StockStatusRepositoryInterface $stockStatusRepository **/
        $result = $stockStatusRepository->getList($criteria);
        $stockStatus = current($result->getItems());
        $stockStatus->getProductId();                 // product id
        $stockStatus->getQty();   // quantity of specified product
        $stockStatus->getStockStatus();     // Could be 
// Magento\CatalogInventory\Model\Stock\Status::STATUS_OUT_OF_STOCK = 0;
// or
// Magento\CatalogInventory\Model\Stock\Status::STATUS_IN_STOCK = 1;

Upvotes: 0

Hassan Ali Shahzad
Hassan Ali Shahzad

Reputation: 2724

if you have product object then just use following:

echo $_product->getExtensionAttributes()->getStockItem()->getQty();

conplete object can be find as follow:

var_dump($_product->getExtensionAttributes()->getStockItem()->getData());

Upvotes: 7

Bartosz Kubicki
Bartosz Kubicki

Reputation: 243

Actually this operation should be performed using \Magento\CatalogInventory\Api\StockRegistryInterface and here we can obtain \Magento\CatalogInventory\Api\Data\StockItemInterface, by product id or sku and we can use bunch of usefull methods to get stock information - linked product. For general stock information I recommend explore other service contracts declared in Magento\CatalogInventory\Api

Example of usage:

<?php
namespace Test\Test\Model;
class Test
{
    protected $_stockRegistry;
    public function __construct(\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry)
    {
        $this->_stockRegistry = $stockRegistry;
    }
    public function getStockItem($productId)
    {
        return $this->_stockRegistry->getStockItem($productId);
    }
}

Upvotes: 5

NIRAJ SHARMA
NIRAJ SHARMA

Reputation: 39

this code help you to get product quantity

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
    echo $StockState->getStockQty($productId);
?>

Upvotes: 3

Robban
Robban

Reputation: 281

If we look at the StockItemRepository class the get method wants parameter $stockItemId, not $productId. Reference:

https://github.com/magento/magento2/blob/develop/app/code/Magento/CatalogInventory/Model/Stock/StockItemRepository.php#L202

I've seen many sites where stock item id IS NOT the same as product id and we should not assume it's the same ID.

To get this working you could use \Magento\CatalogInventory\Model\Stock\Item class instead and load the model by product_id field instead. I am also aware of the website_id and stock_id fields, but as far as I know it's not used (yet) and also existed in M1.

It should look something like this (code not tested):

<?php

namespace Vendor\Module\Model;

use \Magento\CatalogInventory\Model\Stock\Item;

class Mymodel
{
    /**
     * @var Item
     */
    protected $stockItem;

    /**
     * Mymodel constructor.
     *
     * @param Item $stockItem
     */
    public function __construct(Item $stockItem)
    {
        $this->stockItem = $stockItem;
    }

    /**
     * Description
     *
     * @param $productModel
     */
    public function getStockQtyByProductId($productModel)
    {
        try {
            $stockItem = $this->stockItem->load($productModel->getId(), 'product_id');

            return $stockItem->getQty();
        } catch (\Exception $e) {
            echo 'Something went wrong and was not handled: ' . $e->getMessage();
            exit;
        }
    }
}

Upvotes: 10

Related Questions