13

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?

Machavity
  • 30,841
  • 27
  • 92
  • 100
nielsv
  • 6,540
  • 35
  • 111
  • 215

2 Answers2

25

You can use the subDays() method:

$passed = Deployment::where('created_at', '<=', Carbon::now()->subDays(14)->toDateTimeString());
Daniel Alder
  • 5,031
  • 2
  • 45
  • 55
Alex
  • 4,674
  • 5
  • 38
  • 59
  • It seems to work even without `->toDateTimeString()` in the end. `Carbon::now()->subDays(14)`. Is `toDateTimeString()` needed? – Neel Jan 01 '17 at 07:33
  • 12
    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 `<=`. – Daniele Sassoli Mar 20 '17 at 23:30
  • 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. – Hlorofos Nov 01 '18 at 12:24
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

Mauran Muthiah
  • 1,198
  • 9
  • 21