How to Get Product Salable Quantity By Stock Id  in Magento 2

How to Get Product Salable Quantity By Stock Id in Magento 2

Hello Magento folks, welcome back to my new article about getting product salable quantity by stock id.

There is lots of articles and stack exchange answer to get salable qty by SKU but here in this article, I will give you sample code to get salable qty by stock.

We can use an interface Magento\InventorySalesApi\Api\GetProductSalableQtyInterface to get salable qty and use interface Magento\InventorySalesApi\Api\StockResolverInterface for stock information.

Here is the sample code to get salable qty by stock id.

<?php

namespace Mageprince\Catalog\Model;

use Magento\Store\Model\StoreManagerInterface;
use Magento\InventorySalesApi\Api\StockResolverInterface;
use Magento\InventorySalesApi\Api\GetProductSalableQtyInterface;
use Magento\InventorySalesApi\Api\Data\SalesChannelInterface;

class ExampleClass
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var StockResolverInterface
     */
    private $stockResolver;

    /**
     * @var GetProductSalableQtyInterface
     */
    private $getProductSalableQty;

    /**
     * ExampleClass constructor.
     *
     * @param StoreManagerInterface $storeManager
     * @param IsProductSalableInterface $isProductSalable
     * @param StockResolverInterface $stockResolver
     * @param GetProductSalableQtyInterface $getProductSalableQty
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        StockResolverInterface $stockResolver,
        GetProductSalableQtyInterface $getProductSalableQty
    ) {
        $this->storeManager = $storeManager;
        $this->stockResolver = $stockResolver;
        $this->getProductSalableQty = $getProductSalableQty;
    }

    public function getSalableQty($sku)
    {
        $website = $this->storeManager->getWebsite();
        $stock = $this->stockResolver->execute(SalesChannelInterface::TYPE_WEBSITE, $website->getCode());
        return $this->getProductSalableQty->execute($sku, $stock->getStockId());
    }
}

We can skip the stockId parameter from getProductSalableQty to get an array of all available stock qty information.

If you have any questions, feel free to comment below.

Keep liking and sharing. Happy Coding 🙂

Checkout Best Magento 2 Extensions: MageAnts Extensions