How to Update Product Stock MSI Programmatically

Multi-Source Inventory (MSI) is introduced to Magento 2 allowing merchants to handle multiple inventory sources. A common programmatically task is to update product stock for all sources or just for a specific one. Let's see together how you can do that!

Magento 2 MSI is based on the sources which actually a source is a physical stock. Also an import MSI object that we use for updating inventory on each source is the source item. The source item is a relation object that represents the amount of a specific product at a source. So whey we will need to update it, we will need to get this object for a specific store. As you can see below, we get this object using the execute function of the class Magento\InventorySourceDeductionApi\Model\GetSourceItemBySourceCodeAndSku. We will need to know the product SKU and the code of the source we want to update. If we know that we have only one source, then we can update it for the default source. Furthermore, in our example update function below, we see also how you can update the stock for a product in all sources, in case you have more that one and product has the same stock in all of them.

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!

DigitalOcean Referral Badge