Get source item data by source code and SKU Multi Source Inventory(MSI) Magento 2

We can use \Magento\InventoryApi\Api\SourceItemRepositoryInterface class with \Magento\Framework\Api\SearchCriteriaBuilder to get source item data by source code and product SKU.

Here are the sample model class

<?php

namespace Mageprince\Testing\Model;

class SourceItemModel
{
   
    private $searchCriteriaBuilder;

    private $sourceItemRepository;

    public function __construct(
        ...
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
        \Magento\InventoryApi\Api\SourceItemRepositoryInterface $sourceItemRepository
        ...
    ) {
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->sourceRepository = $sourceRepository;
    }

    public function getSourcesItems($souceCode, $sku)
    {
         $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('source_code', $souceCode)
            ->addFilter('sku', $sku)
            ->create();

        $sourceItemData = $this->sourceItemRepository->getList($searchCriteria);
        return $sourceItemData->getItems();
    }
}

Now you can use getSourcesItems() function to get all source items by sources code

$sourceCode = 'test_store';
$sku = 'PO2-113'
$sourceItems = $this->getSourcesItems($sourceCode);

foreach ($sourceItems as $sourceItem) {
    print_r($sourceItem->getData());
}

OUTPUT:

Array
(
    [source_item_id] => 125
    [source_code] => test_store
    [sku] => PO2-113
    [quantity] => 10.0000
    [status] => 1
)

Thank you for reading. Keep sharing 🙂

Leave a Reply

Close Menu