- Laravel
- dates
Make Carbon immutable by default
One line in a service provider makes now() and every date attribute return CarbonImmutable, so addDay() stops changing the date you passed in.
1 min read
Carbon mutates in place: $due = $start->addDays(7) also moves $start, which is the kind of bug that shows up only in a report three weeks later. CarbonImmutable returns a new instance from every call.
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
public function boot(): void
{
Date::use(CarbonImmutable::class);
}After that, now(), today() and model attributes such as created_at are immutable. Code that relied on mutation, for example $date->addDay() on its own line, needs the result assigned back: $date = $date->addDay().