Curious about why Casters can not receive Null Values #722
Unanswered
non-senses
asked this question in
Q&A
Replies: 1 comment 1 reply
-
The reason we're having this is not having to write the following line in every cast: public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): DateTimeInterface|Uncastable
{
if($value === null){
return null;
}
// ...
} In my opinion, if something is null it also shouldn't magically become something, null is null. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Versions:
Laravel 8
PHP 8.1
Laravel-Data ^1
Firstly,
laravel-data
is an incredibly useful package. I've been using it to replace Laravel's resources and requests.For the record, I'm using v1 of the library; I wish I could upgrade, but unfortunately we're stuck with an old version of Laravel.
That being said, pretty often I face an issue that pertains 100% to a design choice you've made, that I can't fully understand.
Here's my example code:
Cast:
Class
And now, the code:
Skipping the key
email
seems to work:However, including
email
as null, doesn't call the caster, nor uses the default value:The behavior seems to come from this check:
Given the same check appears in all versions, I assume you have a very good point on keeping that behavior. However, I think it removes an important functionality by avoiding the use of Casters to build values.
Tinkering with your code, I ended up with this check instead:
This generates the expected behavior in all cases:
I though of creating a PR to include such
isNullable
check in theif
; but I hesitated a lot because you've been insisting for 4 versions on keeping the same behavior. I think I might be missing a big point here, but wasn't able to figure out what it is.I could theoretically fork the package and make the changes I need, but before doing so, I wanted to check with you if you have faced any problem that lead you to make the decision you made.
Thank you
Nicolás
Beta Was this translation helpful? Give feedback.
All reactions