Skip to content
Advertisement

laravel whereBetween doesn’t check last value (date)

I’ve found out that the laravel whereBetween() doesn’t check the last value(date) I give, or maybe my code is wrong. can you check my code or my assumption is correct? and another solution maybe is the time stored in created_at

my code below

$new_from = date('Y-m-d', strtotime($request->from)); // 2020-06-15
$new_to = date('Y-m-d', strtotime($request->to)); // 2020-06-17

$vehicle = Vehicle::findOrFail($request->vehicle);

//if I remove below $check_from and $check_to and check request()->from and to, still gives same data
$check_from = Carbon::parse($new_from)->startOfDay()->toDateTimeString();
$check_to = Carbon::parse($new_to)->startOfDay()->toDateTimeString();

$vehicleDetails = VehicleDetail::where('imei', $vehicle->imei)->whereBetween('created_at', [$check_from, $check_to])->get();

explanation: I have data created at 15 and 17 of June, 2020. but when I try to take from above code, it returns only data from 2020-06-15 but not 17.

when I change request()->to = 2020-06-18 then it gives data from 15 and 17

Thanks in advance.

Advertisement

Answer

Since you’re setting the timestamps for both to the startOfDay, you’re looking for records between 2020-06-15 00:00:00 and 2020-06-17 00:00:00. This means that it won’t find any records for the 17th since any records will be after midnight. Instead, change your end date to be the end of the day.

$check_to = Carbon::parse($new_to)->endOfDay()->toDateTimeString();

This will now get records between 2020-06-15 00:00:00 and 2020-06-17 23:59:59.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement