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?
You can use Carbon subDays() like below:
$data = YOURMODEL::where('created_at', '<=', Carbon::now()->subDays(2)->toDateTimeString())->get();
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With