How to get product salable qty by productId?
Asked
Active
Viewed 665 times
2 Answers
1
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();
}
}
Mital Shah
- 785
- 5
- 11
1
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
Francisco Muniz
- 109
- 10
-
This is useful.but objectmanager method is not good practice – Alshihab Sep 29 '22 at 04:34
-
Hello @Alshihab why is it not a good practice? Thanks – Francisco Muniz Sep 29 '22 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. https://magento.stackexchange.com/questions/117098/to-use-or-not-to-use-the-objectmanager-directly – Alshihab Sep 29 '22 at 11:45
