Get rows where created date is older than 14 days
Asked Answered
L

2

14

This is the case:

In my database I have a table deployments. The rows in the table also have a field created_at. Now I would like to select all rows where the created_date is older than 14 days. But I'm stuck on how to do this with Carbon. My query now looks like this:

$passed = Deployment::where('created_at', '>=', );

Can anyone help me with this?

Loot answered 7/12, 2015 at 16:17 Comment(2)
'now() - interval 14 day'?Residue
Something like this: Carbon::now()->subWeeks(2)Landholder
A
26

You can use the subDays() method:

$passed = Deployment::where('created_at', '<=', Carbon::now()->subDays(14)->toDateTimeString());
Attune answered 7/12, 2015 at 16:36 Comment(3)
It seems to work even without ->toDateTimeString() in the end. Carbon::now()->subDays(14). Is toDateTimeString() needed?Bosley
I know this thread is quite old, but checking for >= will return the elements that are "younger" than 12 days, you say you want to check for elements that are "older", so I think you should be checking for <=.Salta
toDateTimeString() is actually wrong. I suppose the original author is used MySQL as a DB, however when you use MongoDB for example you should pass Carbon object, so it would be treat properly.Erbil
S
3

You can use Carbon::now()->subDays(14)

    $passed = Deployment::where('created_at', '>=', Carbon::now()->subDays(14)->toDateTimeString());

You can read more about Carbon its feature here Carbon Documentation

Shaddock answered 7/12, 2015 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.