0

I need to get product quantity by using SKU. I have this code but give me null:

public function __construct(
    \Magento\Catalog\Model\ProductRepository $productRepository,

        array $data = []
    )
    {

        $this->_productRepository = $productRepository;

    }

public function getProductBySku($sku)
{
  return $this->_productRepository->get($sku);
}



$_product = $this->getProductBySku($itm['sku']);
echo $_product->Qty();
1
  • Did you try $product->getQty()? Feb 4, 2018 at 13:51

2 Answers 2

1
use Magento\CatalogInventory\Model\Stock\StockItemRepository as StockItem;
use Magento\Catalog\Model\Product as Product;

protected $stockItem;

protected $product;


public function __construct(
    ...
    StockItem $stockItem,
    Product $product
    ....
) {
    ....
    $this->stockItem = $stockItem;
    $this->product = $product;
    ....
}

Now you can use like this,

$productId=$this->product->getIdBySku('YOUR_SKU');
if($productId){
    $productStock = $this->stockItem->get($productId);
    $productQty = $productStock->getQty();
}

Using Object Manager (Not recommended)

   $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();           
    $productId = $objectManager->create('Magento\Catalog\Model\Product')->getIdBySku('YOUR_SKU');
    $stockItem = $objectManager->create('\Magento\CatalogInventory\Model\Stock\StockItemRepository');
if($productId){
    $productQty = $stockItem->get($productId)->getQty();
   }
1
  • 4
    wrong. StockItemRepository accepts parameter item_id not product id.
    – Ashar Riaz
    Oct 14, 2020 at 22:18
6

This is better

protected $stockRegistry; 
  public function __construct(

    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
) {

    $this->stockRegistry = $stockRegistry;

}



 public function quantity() {
   return this->stockRegistry->getStockItemBySku($sku)->getQty()
}
2
  • This should be the correct answer. As mentioned in the comments above, the answer by Keyur is not pulling via the correct ID. Additionally - this is the simple/clean method to get the desired infomration.
    – PromInc
    Apr 5, 2021 at 17:56
  • Interface \Magento\CatalogInventory\ApiStockRegistryInterface is deprecated, should not be used . Check devdocs.magento.com/guides/v2.4/inventory/…
    – Nikola
    Sep 15, 2021 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.