How to get product salable qty by productId?
2 Answers
You have to get sku from product id then you can get salable qty by sku
<?php
namespace Mital\InventorySalesAdminUi\Model;
use Magento\InventorySalesAdminUi\Model\GetSalableQuantityDataBySku;
use Magento\Catalog\Api\ProductRepositoryInterface;
class GetSalableQuantityDataBySku
{
private $getSalableQuantityDataBySku;
public function __construct(
GetSalableQuantityDataBySku $getSalableQuantityDataBySku,
ProductRepositoryInterface $productrepository
)
{
$this->getSalableQuantityDataBySku = $getSalableQuantityDataBySku;
$this->productrepository = $productrepository;
}
public function getProductSalableQty()
{
$productid = 12;
$sku = $this->getProductDataUsingId($productid);
$salable = $this->getSalableQuantityDataBySku->execute($sku);
echo json_encode($salable);
}
public function getProductDataUsingId($productid)
{
$product = $this->productrepository->getById($productid);
return $product->getSku();
}
}
You can do this :
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\InventorySalesAdminUi\Model\GetSalableQuantityDataBySku');
$qty = $StockState->execute($product->getSku()); //Being product a product model loaded by your id
$quantity= $qty[0]['qty']; // This is the salable qty
-
This is useful.but objectmanager method is not good practice– AlshihabCommented Sep 29, 2022 at 4:34
-
Hello @Alshihab why is it not a good practice? Thanks Commented Sep 29, 2022 at 11:20
-
According to Magento's core group, you should not use Object Manager in modules because it makes the class lose dependency injection. magento.stackexchange.com/questions/117098/…– AlshihabCommented Sep 29, 2022 at 11:45