Categories: Development

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();
Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago