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
    Feb 16 '17 at 10:00
  • I've edit my answer Feb 16 '17 at 10:09

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!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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