2
public function execute()
{
    // Product Colletion 
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect(['name', 'special_price', 'entity_id']);
    $productColl = [];
    foreach ($collection as $product) {
        // check simple products only
        if ($product->getTypeId() == 'simple') {

            $productX = $this->_productRepository->get($product->getSku());
            $stockItem = $productX->getExtensionAttributes()->getStockItem();
            $qty = $stockItem->getQty();
            print_r($qty);

            $sku = $product->getSku();
            // code for Qty

        }
    }
}

How to get product Qty using SKU In Controller

0

2 Answers 2

4

First load product by sku:

$product = $this->_productRepository->get($sku);

To get stock qty use this:

$StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());

Where $stockState is the instance of \Magento\CatalogInventory\Api\StockStateInterface

3

Get the quantity by using the following code

 protected $_stockRepository;

 protected $_product;

 public function __construct(
   Magento\CatalogInventory\Model\Stock\StockItemRepository $stockRepository,
   Magento\Catalog\Model\Product $product
 ) {
    $this->_stockRepository= $stockItem;
    $this->_product = $product;
 }

And use like this

$productId=$this->_product->getIdBySku('Product_SKU');
if($productId){
$productStock = $this->_stockRepository->get($productId);
$productQty = $productStock->getQty();
}
0

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.