In this post I am going to explain how to get list of all orders or you can say order collection in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | protected $_orderCollectionFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, array $data = [] ) { $this->_orderCollectionFactory = $orderCollectionFactory; parent::__construct($context, $data); } public function getOrderCollection() { $collection = $this->_orderCollectionFactory->create() ->addAttributeToSelect('*') ->setOrder('created_at','desc'); return $collection; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Get order collection $orderCollection = $block->getOrderCollection(); echo "<pre>"; print_r($orderCollection->getData()); echo "</pre>"; if ($orderCollection && count($orderCollection) > 0) { foreach ($orderCollection AS $order) { echo $order->getId() . "<br/>"; echo $order->getStatus() . "<br/>"; } } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $orderCollectionFactory = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\CollectionFactory')->create(); // Get order collection $orderCollection = $orderCollectionFactory ->addAttributeToSelect("*") ->setOrder('created_at','desc'); echo "<pre>"; print_r($orderCollection->getData()); echo "</pre>"; if ($orderCollection && count($orderCollection) > 0) { foreach ($orderCollection AS $order) { echo $order->getId() . "<br/>"; echo $order->getStatus() . "<br/>"; } } |
Thats it. Enjoy Magento 2!!
Leave a Reply