How to filter time in a datime field in eloquent?

3

How can I compare if a time is equal to a time stored in a datetime column using Eloquent?

    
asked by anonymous 25.10.2018 / 19:24

1 answer

5

Considering that you want to disregard the date, but only considering the time, you need to use the TIME function of Mysql to format the column format datetime to time format. Therefore, it is necessary to use the DB::raw() method of Laravel, so that it accepts a Mysql expression in WHERE .

Example:

 // Pega todos os usuários que foram cadastrados às 23:59:01

 Usuario::where(DB::raw('TIME(created_at)'), '=', '23:59:01')->get();

If you want to ignore the seconds, you'll probably have to make a whereBetween , and specify the seconds 00 and 59 . So:

 // Retorna os usuários que foram cadastrados às 13:38, independente dos segundos 

 Usuario::whereBetween(DB::raw('TIME(created_at)'), ['13:38:00', '13:38:59'])->get();

If you need these schedules dynamically, you can use the date function with the H:i:s parameter.

  Usuario::where(DB::raw('TIME(created_at)'), '=', date('H:i:s'))->get()

In addition, it is perfectly possible to set the current date, ignoring the seconds, in the case of whereBetween

Usuario::whereBetween(DB::raw('TIME(created_at)'), [date('H:i:00'), date('H:i:59')])->get();

Update

The HOUR function I had previously placed was wrong. HOUR returns the integer value of the time of a date.

For example:

 2015-01-01 23:40:30

Retonation:

 23

The function TIME returns 23:40:30 , as String.

    
25.10.2018 / 20:18