Magento2 in, we have collection of order. For some bussiness logic we need filter orders collection in specific date range in magento2.

In this blog, I filter order collection in specific date range.

Here we filter order created_at column in date range.

PHP
<?php

declare(strict_types=1);

namespace MageDad\Module\Model;

use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

class OrderFilter
{
	public function __construct(
		private CollectionFactory $orderCollectionFactory
	) {}

	public function getOrderByDateRange()
	{
		$orders = $this->orderCollectionFactory->create();
		$startDate = date("Y-m-d h:i:s", strtotime('2024-01-01')); // start date
 		$endDate = date("Y-m-d h:i:s", strtotime('2024-01-31')); // end date
		$orders->addAttributeToFilter('created_at', ['from' => $startDate, 'to' => $endDate]);
		# echo $orders->getSelect()->__toString(); die();
		# SELECT `main_table`.* FROM `sales_order` AS `main_table` WHERE (`created_at` >= '2024-01-01 12:00:00' AND `created_at` <= '2024-01-31 12:00:00')
 		return $orders;
	}
}

We created blog for collection filter with different type conditions.
Magento2 addAttributeToFilter and addFieldToFilter Condition Types.

I hope this blog is useful to Get Orders Collection between a Date Range in magento2. In case, I missed anything or need to add some more information, Don’t heisted to leave a comment in this blog, I’ll get back with some positive approach.

Keep loving ❤️ Keep inspiring 🤩 Keep liking 👍 No sharing 😂

Write A Comment