Immutable vs mutable date related casts purpose if both are ONE way casts, from raw value to object? #58332
Replies: 2 comments 1 reply
-
|
Hey, good question! I had similar confusion before so let me explain. Youre right that every time you access But heres why immutable still matters:
My recommendation: Use Hope this clears it up! |
Beta Was this translation helpful? Give feedback.
-
|
Good question! The difference between With $user->date_of_birth; // Returns Carbon instance
$dob = $user->date_of_birth;
$dob->addDay(); // This modifies the same object!
// Now both point to the modified date
echo $dob; // 2000-11-12
echo $user->date_of_birth; // Still 2000-11-11 (fresh from attribute)With $user->date_of_birth; // Returns CarbonImmutable instance
$dob = $user->date_of_birth;
$dob->addDay(); // Returns NEW object, original unchanged
echo $dob; // Error or new instanceWhy does this matter? Immutable is safer because you cant accidentally modify a date and cause side effects. For example: // Dangerous with mutable
$endDate = $user->start_date;
$endDate->addDays(30); // Oops, now start_date reference is also changed if cached
// Safe with immutable
$endDate = $user->start_date->addDays(30); // Returns new objectIn your example, you are seeing correct behavior - each call to TL;DR: Use |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Acc. to this discussion #57627 (comment) the date and datetime are one way castable, meaning they are not cast back into the $attributes like Class Casts or Attribute Casts:
Question is:
What is the purpose of immutable date time vs date time then:
vs
?
results in
Beta Was this translation helpful? Give feedback.
All reactions