Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eggplantSword's avatar

Eloquent query returns empty if date is today

I'm trying to execute a simple query but the query returns empty when the date range is using today's date but in the database I can see there is data that should be brought.

This is the query, on a model called Location

$query = self::query()->where('customer_id', '=', sysconf());

        if (isset($columns)) {
            $query->select($columns);
        }

        if (isset($filters['user_id'])) {
            $query->where('user_id', $filters['user_id']);
        }

        if (isset($filters['range'])) {
            $query->whereBetween('date', $filters['range']); 
        }

        $query->orderBy('created_at', 'asc');

		Log::info($filters);
		Log::info($query->toSql());
		Log::info($query->getBindings());

        $result = $query->get();

        return $result;

This is the results of the Logs

FILTERS
array (
  'employee_id' => 23,
  'user_id' => 23,
  'range' => 
  array (
    0 => '2022-05-03 00:00:00',
    1 => '2022-05-03 23:59:59',
  ),
  'day' => 'tuesday',
  'date_first' => '2022-05-03T15:48:00.000Z',
  'date' => '2022-05-03',
)  

QUERY TO SQL
 select `latitude`, `longitude`, `date`, `speed` from `locations` where `customer_id` = ? and `user_id` = ? and `date` between ? and ? order by `created_at` asc  

QUERY BINDINGS
 array (
  0 => 2,
  1 => 23,
  2 => '2022-05-03 00:00:00',
  3 => '2022-05-03 23:59:59',
)  

The date field in the db is in this format 2022-05-04 00:01:38. If I do any other past date except today it works no problems, what am I doing wrong?

0 likes
1 reply
Nakov's avatar

The issue is because whereBetween is exclusive, try this approach:

 $query->whereDate('date', '>=', $filters['range'])
	->whereDate('date', '<=', $filters['range']); 

Please or to participate in this conversation.