Check between two date with Eloquent time


Hello, I need to make a query between two dates with hours

$data = Modelo::whereBetween('created_at', ['2018/11/10 12:00', '2018/11/11 10:30'])

But when making this query it brings all the results between the dates without taking into account the hours.

Dates are automatically saved with Eloquent

And apart I do the following to format the dates I'm going to look for:

Carbon::now()->parse($date)->format('Y-m-d H:i:s');
asked by Alberto Ortega 27.11.2018 в 19:35

1 answer


To be able to search between 2 dates, within Laravel you must proceed as follows:

If the field of your database is of type DATETIME the structure of your query should be as follows:

$data = Modelo::whereBetween('created_at', ['2018/11/10 12:00:00', '2018/11/11 10:30:00'])->get();

Or also

$data = Modelo::whereBetween('created_at', ['2018-11-10 12:00', '2018-11-11 10:30'])

You must keep in mind that for the calculation to be done as you require it; Your field must have this structure:

YYYY-MM-DD HH:MM:SS - > 2018-11-12 12:52:12

If for example you are going to occupy Carbon

It may look like this:

$fechaFormateada = Carbon::now();
$data = User::whereBetween('created_at', ['2018-11-24 15:49:02', $fechaFormateada])  
return $data;

What about the dateFormatted property?

If you do this:


You will get the following as a result

object(Carbon\Carbon)#485 (3) { ["date"]=> string(26) "2018-11-28 00:53:33.425487" 
                                ["timezone_type"]=> int(3) ["timezone"]=> 
                                 string(3) "UTC" }

That as you can see if it includes the seconds; to respect the data format required by the field DATETIME

answered by 28.11.2018 / 01:57