You need to create a copy() of an existing Carbon instance ($now).
$now->copy()->subDays($i)->format('Y-m-d')
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am using Carbon to query data from the past two weeks, so I have a variable $now for today's date, and I loop the query over a for-loop and use $now->subDays($i) to get today, yesterday, the day before, etc, up to 14 days ago. I knew something was wrong because the query was returning null results (i.e it was trying to query for a date that didn't exist in the set), so I dumped the actual dates that were being passed in and formatted them as $now->subDays($i)->format('Y-m-d') and this is what I got:
"2022-03-31"
"2022-03-30"
"2022-03-28"
"2022-03-25"
"2022-03-21"
"2022-03-16"
"2022-03-10"
"2022-03-03"
"2022-02-23"
"2022-02-14"
"2022-02-04"
"2022-01-24"
"2022-01-12"
"2021-12-30"
The dates are incorrect... Obviously 2021-12-30 is not 14 days before 2022-03-31, and I have no idea what is happening to cause this.
Here is the raw for-loop that dumps the dates and decreases the date by one day:
$date = Carbon::now();
for ($i = 0; $i < 14; $i++) {
dump($date->subDays($i)->format('Y-m-d'));
}
You need to create a copy() of an existing Carbon instance ($now).
$now->copy()->subDays($i)->format('Y-m-d')
Please or to participate in this conversation.