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

Sinres's avatar

Laravel eloquent where date is equal or smaller than DateTime

Hello Guys!

How I can take date where date is equal or smaller than date time?

This is my code:

$current_date = Carbon::now();
$date = Carbon::parse($current_date)->addMonths(24)->format('d-m-Y');
       
       $deviceInspections = DB::table('device_inspections')
            ->orderBy('created_at', 'desc')
            ->where('deleted_at', NULL)
            ->whereDate('inspection_date', '<=', $date)
            ->paginate(20);

inspection_date contains the date:

31-01-2020

And $date contains the date:

15-02-2021

As a result, he does not get any records why?

0 likes
6 replies
manelgavalda's avatar
Level 50

I think the problem is with ->format('d-m-Y'). If you are using this format in order to compare just the date without comparing the time, you can use today with carbon:

$date = Carbon::today()->addYears(2);

$deviceInspections = DB::table('device_inspections')
    ->orderBy('created_at', 'desc')
    ->where('deleted_at', NULL)
    ->whereDate('inspection_date', '<=', $date)
    ->paginate(20);
7 likes
Nakov's avatar

Are you sure that the format in the database is d-m-Y, is it maybe Y-m-d which is the default for a date?

Sinres's avatar

@manelgavalda and @nakov you were right with my problem. Problem was with data format I changed format to Y-m-d and all is fine but maybe there is a solution to display data in a format d-m-Y? Any ideas?

Nakov's avatar

@sinres you can change the format of the date using the $casts field in the model, but that won't help with the query. So if you just want to display the date in a different format, add this in your model class containing the inspection_date field:

protected $casts = [
    'inspection_date' => 'date:d-m-Y'
];
1 like
fahdshaykh's avatar

Here is my logic: if you are comparing date then your method should be whereDate and if your comparing complete datetime then your method will be only where:

$calendar_alert = DB::table('calendar_alerts')->whereDate('when', '=', now()->format('Y-m-d'))->where('when', '>', now()->format('H:i:s'))->get();

Please or to participate in this conversation.