Carbon immutable vs mutable

November 9th, 2022

Carbon date is a mutable object

That means that any modifications to that object modify or mutate the original value.

1$start_date = new Carbon('2022-01-01');
2$end_date = $start_date->addMonth();
3 
4dd($start_date) // 2022-02-01 just like $end_date, $start_date was mutated in the process
5dd($end_date) // 2022-02-01

How can we fix that?

We can change the Carbon Object to Immutable, so it doesn't change original value. That can be done with: Carbon clone date or new CarbonImmutable

Carbon clone date

Before addMonth clone Carbon date, so that initial value of carbon date doesn't change

1$start_date = new Carbon('2022-01-01');
2$end_date = $start_date->clone()->addMonth();
3 
4dd($start_date) // 2022-01-01
5dd($end_date) // 2022-02-01

CarbonImmutable

Create CarbonImmutable date instead of just Carbon date, which doesn't change its value after addMonth

1$start_date = new CarbonImmutable('2022-01-01');
2$end_date = $start_date->addMonth();
3 
4dd($start_date) // 2022-01-01
5dd($end_date) // 2022-02-01

Related Posts