Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento 2: Get Product Stock Quantity and Other Stock Information

Tags:

magento2

Magento 2: Get Product Stock Quantity and Other Stock Information

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

like image 959
VishalPandita Avatar asked Nov 30 '22 09:11

VishalPandita


1 Answers

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;
        }
    }
}
like image 200
Robban Avatar answered Dec 23 '22 20:12

Robban