Magento 2 Get Inventory Source Code from Shipment

Magento offers MSI (Multi Souce Invetnory) features that allow adding multiple sources or locations for delivery. You have to choose the source of inventory at the time of shipment. Now if your requirement is to know which inventory source is selected for the existing shipment then you can do it and to know how to do it, keep reading 🙂

How to get inventory source code of Magento shipment

You can use this code to get the shipment source code.
$shipment->getExtensionAttributes()->getSourceCode()

Here is the full code of how to load the shipment by ID and then get the source code in Magento 2

<?php
namespace Dhairvi\Test\Model;

class ClassName
{
    /**
     * @var \Magento\Sales\Api\ShipmentRepositoryInterface
     */
    protected $_shipmentRepositoryInterface;

    /**
     * @param \Magento\Sales\Api\ShipmentRepositoryInterface $shipmentRepositoryInterface
     */
    public function __construct(
        \Magento\Sales\Api\ShipmentRepositoryInterface $shipmentRepositoryInterface
    ) {
        $this->_shipmentRepositoryInterface = $shipmentRepositoryInterface;
    }

    /**
     * Get shipment data using shipping ID.
     * 
     * @param $shipmentId
     * @return $sourceCode
     */
    public function getInventorySourceCode($shipmentId)
    {
        $sourceCode = null;
        try {
            $shipment = $this->_shipmentRepositoryInterface->get($shipmentId);
            $sourceCode = $shipment->getExtensionAttributes()->getSourceCode();
            
        } catch (Exception $exception)  {
            //error
        }

        return $sourceCode;
    }
}

This is how you can get the shipment source code in Magento 2.