How to Get Product Salable Quantity in Magento 2
Introduction:
In a Magento 2 e-commerce store, knowing the available salable quantity of a product is crucial for various reasons, including inventory management and displaying stock availability to customers. In this tutorial, we'll explore how to retrieve the product's salable quantity using Magento 2 code.
Example:
To get the salable quantity of a product in Magento 2, you can use the StockStateProvider class. Here's an example of how to do it in a custom PHP script or within a Magento module:
<?php
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Store\Model\StoreManagerInterface;
use Magento\CatalogInventory\Api\StockStateProviderInterface;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
/** @var StockStateProviderInterface $stockStateProvider */
$stockStateProvider = $bootstrap->getObjectManager()->get(StockStateProviderInterface::class);
/** @var StoreManagerInterface $storeManager */
$storeManager = $bootstrap->getObjectManager()->get(StoreManagerInterface::class);
$storeId = $storeManager->getStore()->getId();
$productId = 1; // Replace with the ID of the product you want to check.
try {
$salableQty = $stockStateProvider->getStockQty($productId, $storeId);
echo "Salable Quantity for Product #$productId: $salableQty";
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
In this example, we first include the necessary Magento files and classes. Then, we get an instance of the StockStateProviderInterface and the store ID. Replace $productId with the ID of the product you want to check, and the script will output the salable quantity for that product.
Conclusion:
Knowing how to get the salable quantity of a product in Magento 2 is essential for efficient inventory management and customer experience. The StockStateProvider class provides a straightforward way to retrieve this information programmatically.