How to get Shipment item collection by shipment item id Magento 2?

You can retrieve the shipment item data by shipment item id using Magento 2 by Shipment Item RepositoryInterface.

Used Shipment item repository interface to get shipment data:
Magento\Sales\Api\ShipmentItemRepositoryInterface

An interface contains the get(int $id) method to fetch records by shipment id.

using the above repository, You need to pass the shipment item id from the sales_shipment_item table.

Please be careful of shipment_item_id will be used and not the shipment_id from the shipment table.

<?php
namespace Jesadiya\ShipItem\Model;

use Exception;
use Magento\Sales\Api\Data\ShipmentItemInterface;
use Magento\Sales\Api\ShipmentItemRepositoryInterface;
use Psr\Log\LoggerInterface;

class Demo
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var ShipmentItemRepositoryInterface
     */
    private $shipmentItemRepository;

    public function __construct(
        LoggerInterface $logger,
        ShipmentItemRepositoryInterface $shipmentItem
    ) {
        $this->logger = $logger;
        $this->shipmentItemRepository = $shipmentItemRepository;
    }

    /**
     * @return ShipmentItemInterface[]|null
     */
    public function getShipmentItem(int $shipmentItemId): ?array
    {
        $shipmentItems = null;
        try {
            $shipmentItems = $this->shipmentItemRepository->get($shipmentItemId);
        } catch (Exception $exception)  {
            $this->logger->critical($exception->getMessage());
        }
        return $shipmentItems;
    }

Pass shipment item id as arguments in the method getShipmentItem() and you can fetch the shipment item as a result.

$shipmentItemId = 100;
$shipmentData = $this->getShipmentItem($shipmentItemId);
var_dump($shipmentData->getData());

The output will be from the sales_shipment_item table,

array (size=12)
  'entity_id' => string '100' (length=3)
  'parent_id' => string '211' (length=3)
  'row_total' => null
  'price' => string '270.0000' (length=8)
  'weight' => string '100.0000' (length=8)
  'qty' => string '1.0000' (length=6)
  'product_id' => string '110' (length=3)
  'order_item_id' => string '1121' (length=4)
  'additional_data' => null
  'description' => null
  'name' => string 'test product name' (length=17)
  'sku' => string 'test1234' (length=8)

You can get the shipment item record from the item id in Magento 2 with the simple code snippet.

From the above result, you can fetch the required data as per your requirement.

One Reply to “How to get Shipment item collection by shipment item id Magento 2?”

Comments are closed.