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
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();
   }
0

Did you try $product->getQty()?

0

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()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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