Laravel Eloquent query builder date and time based queries

Using The Laravel Eloquent query builder to fetch and filter records based on their date and time.

Here are examples for when you need to retrieve records that are older than, newer than, at a specific time or between two dates.

Fetch records that are older than 5 minutes:

Post::where('created_at', '<=', Carbon::now()->subMinutes(5)->toDateTimeString())->get();

Fetch records that are older than 6 hours:

Post::where('created_at', '<=', Carbon::now()->subHours(6)->toDateTimeString())->get();

Fetching older than 1 day (24 hours):

Post::where('created_at', '<=', Carbon::now()->subDay(1)->toDateTimeString())->get();

Fetch records created within the past hour:

Post::where('created_at', '>=', Carbon::now()->subHour()->toDateTimeString())->get();

Fetch created in the past 2 weeks:

Post::where('created_at', '>=', Carbon::now()->subWeeks(2)->toDateTimeString())->get();

Fetching when less than 1 day old:

Post::where('created_at', '>=', Carbon::now()->subDay()->toDateTimeString())->get();

Fetch records that are in between two dates (Jan 1st 2023 to Jan 10th 2023):

Post::whereBetween('created_at', ['2023-01-01', '2023-01-10'])->get();

Fetch records that were created on a certain date, regardless of the time:

Post::whereDate('created_at', '2020-01-01')->get();

Where a certain time (H:i:s format):

Post::whereTime('created_at', '=', '10:00:00')->get();

Where a day of the month (1-31)

Post::whereDay('created_at', '1')->get();

Where month of the year (1-12)

Post::whereMonth('created_at', '5')->get();

Where a year

Post::whereYear('created_at', '2021')->get();