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.
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.
// 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
$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!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply