How to get source by shipment Id in Magento 2 MSI

Hello guys! In this article, I will show you how we can get the assigned source of the order by shipment id.

We can use the default Magento_InventoryShipping class Magento\InventoryShipping\Model\ResourceModel\ShipmentSource\GetSourceCodeByShipmentId

Here is the sample code:

<?php

namespace Mageprince\Test\Model;

use Magento\InventoryShipping\Model\ResourceModel\ShipmentSource\GetSourceCodeByShipmentId;

class SampleClass
{
	protected $filter;

	public function __construct(
		...
	    GetSourceCodeByShipmentId $sourceCodeByShipmentId,
	 	...
	) {
	    $this->sourceCodeByShipmentId = $sourceCodeByShipmentId;
	}

	public function getSource($shipmentId)
	{
		return $this->sourceCodeByShipmentId->execute($shipmentId);
	}
}

Here is sample usage

$shipmentCollection = $order->getShipmentsCollection();

foreach ($shipmentCollection as $shipment) {
    $shipmentId = (int)$shipment->getId();
    $orderSources[] = $this->sourceCodeByShipmentId->execute($shipmentId);
}

print_r($orderSources); //All sources assigned to order

OUTPUT:

Array
(
    [0] => Warehouse
    [1] => Brisbane
    [2] => Fountain
)

If you have any questions or suggestion fell free to comment below.

Thanks for reading. Keep sharing 🙂