fransyozef
fransyozef

Reputation: 574

Laravel Eloquent find rows where date older than 2 days

I'm trying to fetch rows based on the "created_at" field that are older than (for example) 2 days.

I'm using Laravel Eloquent. Can somebody help me with this?

Upvotes: 20

Views: 30821

Answers (2)

thisiskelvin
thisiskelvin

Reputation: 4202

You can use the whereDate() eloquent method to run a query against dates.

Model::whereDate('created_at', '<=', now()->subDays(2)->setTime(0, 0, 0)->toDateTimeString())->get();

The now() is a laravel helper function to get a carbon instance of the current date and time.

NOTE: We set the time using the setTime() method so that it starts from the beginning of the day.

Update: It is also possible to use ->startOfDay().

Upvotes: 13

Ugur Kazdal
Ugur Kazdal

Reputation: 678

You can use Carbon subDays() like below:

$data = YOURMODEL::where('created_at', '<=', Carbon::now()->subDays(2)->toDateTimeString())->get();

Upvotes: 47

Related Questions