Get rows where created date is older than 14 days

12,031

Solution 1

You can use the subDays() method:

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

Solution 2

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

Share:
12,031
nielsv
Author by

nielsv

Updated on June 13, 2022

Comments

  • nielsv
    nielsv almost 2 years

    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?

  • Neel
    Neel over 7 years
    It seems to work even without ->toDateTimeString() in the end. Carbon::now()->subDays(14). Is toDateTimeString() needed?
  • Daniele Sassoli
    Daniele Sassoli about 7 years
    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 <=.
  • Hlorofos
    Hlorofos over 5 years
    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.