How to get all the Items of Order In Magento 2?

The best way to get all Order Items in Magento 2 is by using $order->getAllVisibleItems().

Also, we have the $order->getAllItems() function that returns an array of all items of the cart with the configurable simple product. So we will be using both functions according to their uses.

We will be getting three products a simple product, the associated product, and the parent product, if you use $order->getAllItems(). So you have to use the $order->getAllVisibleItems() method to get the original product.

This is how the different methods to get items from an order work:

getItems(): returns array of items from loaded order item collection

getAllItems(): returns an array of all items that are not marked as deleted

getAllVisibleItems(): returns an array of all items that are not marked as deleted and do not have a parent item

So to get only the configurable product and not its associated product, getAllVisibleItems() is the correct method.

Check here to how to get the Order details using Repository.

$order = $this->orderRepository->get($orderId);

$orderItems = $order->getAllVisibleItems();

foreach ($orderItems as $item) {
    echo $item->getId();
    echo $item->getSku();
    echo $item->getProductType();
}

Using the above example code you can use to get Items from Order in Magento 2.

Leave a Reply