Request Quote

How to programmatically create shipment in magento2

Here we learn in Magento2- how to create shipment of an order programmatically.
If you want to create custom quote and order programmatically then you can check this blog Create Quote & Order Programmatically

Create Shipment of an order-

 * Webkul Software.
 * @category  Webkul
 * @package   Webkul_Test
 * @author    Webkul
 * @copyright Copyright (c) 2010-2018 Webkul Software Private Limited (
 * @license
namespace Webkul\Test\Controller\Order;
class CreateShipment extends Magento\Framework\App\Action\Action
     * @var \Magento\Sales\Api\OrderRepositoryInterface
    protected $_orderRepository;

     * @var \Magento\Sales\Model\Convert\Order
    protected $_convertOrder;

     * @var \Magento\Shipping\Model\ShipmentNotifier
    protected $_shipmentNotifier;

     * @param Context                                     $context
     * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
     * @param \Magento\Sales\Model\Convert\Order          $convertOrder
     * @param \Magento\Shipping\Model\ShipmentNotifier    $shipmentNotifier
    public function __construct(
        Context $context,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Sales\Model\Convert\Order $convertOrder,
        \Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier
    ) {
        $this->_orderRepository = $orderRepository;
        $this->_convertOrder = $convertOrder;
        $this->_shipmentNotifier = $shipmentNotifier;

     * Test Order Create Shipment Controller
    public function execute()
        $orderId = 1;
        $order = $this->_orderRepository->get($orderId);

        // to check order can ship or not
        if (!$order->canShip()) {
            throw new \Magento\Framework\Exception\LocalizedException(
            __('You can't create the Shipment of this order.') );

        $orderShipment = $this->_convertOrder->toShipment($order);

        foreach ($order->getAllItems() AS $orderItem) {

         // Check virtual item and item Quantity
         if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {

         $qty = $orderItem->getQtyToShip();
         $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qty);


        try {

            // Save created Order Shipment

            // Send Shipment Email
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\LocalizedException(

In this way, you can create shipment for a particular complete order.
If you want to create the invoice of an order in Magneto 2, you can check the wonderful blog from here Create Invoice Programmatically

Hope it will help you. Thank you.


. . .


Add Your Comment

Be the first to comment.

Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again