How to get and update stock status in Magento 2.3 MSI

The Old Way

The old way of getting stock info from Magento 2 was using stockRegistry and it would output or input an array.

$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
$stockRegistry = $objectManager->create('\Magento\CatalogInventory\Api\StockRegistryInterface');

$sku="STARTNET_ITEM_123";
$product=$productRepository->get($sku);

$stockdata = $stockRegistry->getStockStatus($product->getId(), 1); // for store id = 1

var_dump($stockdata->getData());

array(7) {
["product_id"]=>
string(5) "12345"
["website_id"]=>
string(1) "0"
["stock_id"]=>
string(1) "1"
["qty"]=>
float(106)
["stock_status"]=>
int(1)
["sku"]=>
string(7) "STARTNET_ITEM_123"
["type_id"]=>
string(6) "simple"
}

// UPDATE THE QUANTITY AND STATUS
$qty=161;
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($qty); // set qty or whatever else
$stockItem->setIsInStock(false);

$stockRegistry->updateStockItemBySku($sku, $stockItem); // update the item

The New MSI Model

Now though, Magento 2 has moved to a Multi-store Inventory(MSI) system. So there are multiple inventory sources.
Luckily the default one is called "default". Therefore this is the new method of getting and updating stock levels.

$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');

$getSourceItemsBySku=$objectManager->create('Magento\Inventory\Model\SourceItem\Command\GetSourceItemsBySku');
$sourceItemFactory=$objectManager->get('\Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory');
$sourceItemsSaveInterface=$objectManager->create('\Magento\InventoryApi\Api\SourceItemsSaveInterface');

$sku="STARTNET_ITEM_123";
$product=$productRepository->get($sku);

$asource="default";

// GET STOCK ITEM DETAILS

$sourceItems = $getSourceItemsBySku->execute($product->getSku());
foreach ($sourceItems as $sourceItemId => $sourceItem) {
    echo $sourceItem->getSku() . ','; 
    echo $sourceItem->getSourceCode() . ','; // The actual source code e.g: warehouse_london
    echo $sourceItem->getStatus() . ','; // is it sellable or not
    echo $sourceItem->getQuantity(); // the quantity for the current source
	echo "\n";
	if ($sourceItem->getSourceCode()==$asource) { $aqty = $sourceItem->getQuantity(); }
}

// UPDATE STOCK ITEM
$sourceItem = $sourceItemFactory->create();
$sourceItem->setSourceCode($asource); // the source
$sourceItem->setSku($sku); //Configurable product SKU
$sourceItem->setQuantity($aqty); //Total quantity is the sum of all variation quantities
//status is either SourceItemInterface::STATUS_IN_STOCK or SourceItemInterface::STATUS_OUT_OF_STOCK);
$sourceItem->setStatus(\Magento\InventoryApi\Api\Data\SourceItemInterface::STATUS_OUT_OF_STOCK);

$sourceItemsSaveInterface->execute([$sourceItem]); // save the stock status

// DONE

Leave a Reply