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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago