Hello guys! In this article, I will show you how we can get the assigned source of the shipment by shipment id.
There are two way to get source by shipment id
Method 1: We can use the Magento Inventory shipping class Magento\InventoryShipping\Model\ResourceModel\ShipmentSource\GetSourceCodeByShipmentId
Method 2: Or by using Magento shipment repository Magento\Sales\Api\ShipmentRepositoryInterface
Here is the sample code for Method 1:
<?php namespace Mageprince\Test\Model; use Magento\InventoryShipping\Model\ResourceModel\ShipmentSource\GetSourceCodeByShipmentId; class SampleClass { protected $sourceCodeByShipmentId; public function __construct( GetSourceCodeByShipmentId $sourceCodeByShipmentId, ) { $this->sourceCodeByShipmentId = $sourceCodeByShipmentId; } public function getSource($shipmentId) { return $this->sourceCodeByShipmentId->execute($shipmentId); } }
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 )
Here is the sample code for Method 2:
<?php namespace Mageprince\Test\Model; use Magento\Sales\Api\ShipmentRepositoryInterface; class SampleClass { protected $shipmentRepository; public function __construct( ShipmentRepositoryInterface $shipmentRepository ) { $this->shipmentRepository = $shipmentRepository; } public function getSource($shipmentId) { $shipment = $this->shipmentRepository->get($shipmentId); return $shipment->getExtensionAttributes()->getSourceCode(); } }
If you have any questions or suggestion fell free to comment below.
Thanks for reading. Keep sharing 🙂