I want to filter collection according :

  • start date < today
  • end date > today

I try this but my getSlides() function return empty results


namespace Vendor\Module\Block;

use Magento\Backend\Block\Template\Context;
use Vendor\Module\Api\Data\SlideInterface;
use Vendor\Module\Model\ResourceModel\Slide\CollectionFactory as SlideCollectionFactory;

class Carrousel extends \Magento\Framework\View\Element\Template
    /** @var \Vendor\Module\Model\ResourceModel\Slide\CollectionFactory */
    protected $slideCollection;

     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Vendor\Module\Model\ResourceModel\Slide\CollectionFactory $slideCollection
     * @param array $data
    public function __construct(
        Context $context,
        SlideCollectionFactory $slideCollection,
        array $data = []
        parent::__construct($context, $data);
        $this->slideCollection = $slideCollection;

    public function getSlides()
        $now = new \DateTime();

        $slides = $this->slideCollection->create()
        ->addFilter('startDate', ['lteq' => $now->format('Y-m-d H:i:s')])
        ->addFilter('endDate', ['gteq' => $now->format('Y-m-d H:i:s')]);

        return (count($slides) > 0) ? $slides : false;

Please help me...

  • Can you provide more information on the collection you are filtering? Is this a 3rd party module or custom? It's common practice in m1/m2 for database columns to be named using underscores i.e. start_date
    – Ash Smith
    Commented Feb 16, 2017 at 10:00
  • I've edit my answer Commented Feb 16, 2017 at 10:09

2 Answers 2


Has force to seek and test several solutions I finally found !

Like I use CollectionFactory object I have to use addFieldToFilter() and not addFilter().

$slides = $this->slideCollection->create()
        ->addFieldToFilter('startDate', ['lteq' => $now->format('Y-m-d H:i:s')])
        ->addFieldToFilter('endDate', ['gteq' => $now->format('Y-m-d H:i:s')]);

It works perfectly!

  • 1
    This is super awesome, thankyou! Commented Jan 7, 2021 at 17:26
  • 1
    It might be helpful to also add an OR null condtion to also fetch those records which do not have explicitly set a from or or date. ->addFieldToFilter('from_date', [['lteq' => $today], ['null' => true]]) the same goes for 'to_date'
    – Akif
    Commented Oct 12, 2022 at 8:54

I would like to add one more answer :

If Date field is optional then you can use below code for date filter

$slides = $this->slideCollection->create()
        ->addFieldToFilter('startDate', [['lteq' => $now->format('Y-m-d H:i:s')], ['null' => true]])
        ->addFieldToFilter('endDate', [['gteq' => $now->format('Y-m-d H:i:s')], ['null' => true]]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.