How to create shipment programmatically in magento2

If we need to programmatically create shipment for an order then you can create by following way.

// Load the order
$order = $this->_objectManager->create('Magento\Sales\Model\Order')
    ->loadByAttribute('increment_id', '000000001');
$order = $this->_objectManager->create('Magento\Sales\Model\Order')

// Check if order can be shipped or has already shipped
if (! $order->canShip()) {
    throw new \Magento\Framework\Exception\LocalizedException(
                    __('You can\'t create an shipment.')

// Initialize the order shipment object
$convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order');
$shipment = $convertOrder->toShipment($order);

// Loop through order items
foreach ($order->getAllItems() AS $orderItem) {
    // Check if order item has qty to ship or is virtual
    if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {

    $qtyShipped = $orderItem->getQtyToShip();

    // Create shipment item with qty
    $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

    // Add shipment item to shipment

// Register shipment


try {
    // Save created shipment and order

    // Send email

} catch (\Exception $e) {
    throw new \Magento\Framework\Exception\LocalizedException(
  • Uncategorized

8 thoughts on “How to create shipment programmatically in magento2

  1. Thank you for your effrt, but is it ok to use the _objectManager here, cause I’ve read couple of articles regarding this, saying that its not recommended to use the _objectManager.
    if is it ok, how did you access it (_objectManager)? is it by initiate an instance of \Magento\Framework\ObjectManagerInterface in the constructor?

  2. Hi ,
    Nice Work!
    but you have to add two lines for code at the beginning,
    protected $objectManager;
    $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();


  3. Hi Sohelrana,

    thanks for the article. May i ask how do we add tracking number, carrier, comments to the shipment as well? Lots of magento 1 articles out there regarding that, but none that i can find on magento 2.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.