Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 710
fransyozef Avatar asked Sep 21 '18 09:09

fransyozef


2 Answers

You can use Carbon subDays() like below:

$data = YOURMODEL::where('created_at', '<=', Carbon::now()->subDays(2)->toDateTimeString())->get();
like image 132
Ugur Kazdal Avatar answered Nov 19 '22 05:11

Ugur Kazdal


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().

like image 28
thisiskelvin Avatar answered Nov 19 '22 06:11

thisiskelvin