Laravel 8 query builder filter results by two datetime columns with whereDate

I’m using Laravel 8’s query builder to return a particular result from my database. I’ve got my query partially working with most of what I need but am having some issues trying to filter based on two particular datetime columns.

I’ve got two columns: period_from and period_to, I’d like to be able to return the relevant results after a given date on the period_from column, but before the period_to column with a different date, this is what I’ve got so far:

$events = GoogleAnalytics::where('event_category', $category)
                        ->where('event_action', $action)
                        ->whereDate('period_from', $dateFrom)
                        ->whereDate('period_to', $dateTo)
                        ->orderBy('created_at', 'desc')
                        ->first();

This unfortunately doesn’t work, I can get results if I drop the period_to column, but I need to filter between the two dates. Why isn’t this working? Can I have some guidance please? 🙂

Answer

Try to add the operators along with the where query.

$events = GoogleAnalytics::where('event_category', $category)
                    ->where('event_action', $action)
                    ->where('period_from', '<', $dateFrom)
                    ->where('period_to', '>', $dateTo)
                    ->orderBy('created_at', 'desc')
                    ->first();