Back to Top

How to save and get source inventory in Magento 2

Updated 1 March 2024

In Magento 2.3, a new feature was introduced Multi-Source Inventory aka MSI. It changes how the product inventory works. With this feature, a product can be assigned multiple sources and each source can have a different quantity of the product.

In this blog, I will explain how to save product quantities for multiple sources and how to retrieve the saved quantities. Here I will create a product with SKU “test_product” and two sources with source code “test_source” and “test_source2“. Please make sure that you have added the sources in the stock and selected the source channel in the stock.

1. Save product quantities for multiple sources

public function __construct(
    .....
    \Magento\InventoryCatalogApi\Model\SourceItemsProcessorInterface $sourceItemsProcessor
) {
    .....
    $this->sourceItemsProcessor = $sourceItemsProcessor;
}

public function execute()
{
    $data = [
        ['source_code'=>'test_source', 'status'=>1, 'quantity'=>50],
        ['source_code'=>'test_source2', 'status'=>1, 'quantity'=>80]
    ];
    
    $this->sourceItemsProcessor->execute(
        'test_product',
        $data
    );
}
Output of above code

Please note that if you want to update the quantity for a single product then you can not just pass a single array in the data. If you do then it will remove the previous sources. So now if you do,

$data = [
    ['source_code'=>'test_source', 'status'=>1, 'quantity'=>100]
];

$this->sourceItemsProcessor->process(
    'test_product',
    $data
);

then it will remove the other source like shown below

Searching for an experienced
Magento 2 Company ?
Find out More
Output of above code

2. Get the product’s multi-source quantities

public function __construct(
    ......
    \Magento\InventoryCatalogAdminUi\Model\GetSourceItemsDataBySku $sourceDataBySku
) {
    ......
    $this->sourceDataBySku = $sourceDataBySku;
}

public function execute()
{
    $data = $this->sourceDataBySku->execute('test_product');
}

It returns the source-wise quantities in the array.

Array
(
    [0] => Array
        (
            [source_code] => test_source
            [quantity] => 50
            [status] => 1
            [name] => Test Source
            [source_status] => 1
        )

    [1] => Array
        (
            [source_code] => test_source2
            [quantity] => 80
            [status] => 1
            [name] => Test Source 2
            [source_status] => 1
        )

)

To get the saleable quantity you can check,

https://webkul.com/blog/get-salable-quantity-in-magento-2-3/

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Iyappan Perumal
    • Rajan Dimri (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home