Replies: 2 comments 1 reply
-
I think you should solve this using a custom cast: https://spatie.be/docs/laravel-data/v2/as-a-data-transfer-object/casts Within the cast you can do anything you want with an empty string (convert to null, convert to now or whatever). For example, I use this cast to use Carbon::parse instead of a fixed format: class CarbonParseCast extends Cast
{
public function __construct(
protected ?string $type = null,
) {
}
/**
* @param array<string,mixed> $context
*/
public function cast(DataProperty $property, mixed $value, array $context): DateTimeInterface|Uncastable
{
try {
$type = $this->type ?? Carbon::class;
return $type::parse($value);
} catch (\Throwable $th) {
}
return Uncastable::create();
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
I wanted to maintain the benefits of the built in DateTimeInterfaceCast, just return null if the string is empty. Here's what I came up with:
|
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
Uh oh!
There was an error while loading. Please reload this page.
-
What can I do when a date is provided as empty string during Data creation?
As far as I see, this package can deal with:
Optional
)null
)Casts
andTransformers
)However, when I receive data where a date is provided as an empty string, I get an error
Could not cast date `` into a `Carbon\Carbon` using formats: Y-m-d, d.m.Y
The incoming data is from an external API so I have no possibility of tampering with it before (other than ugly kludges).
Beta Was this translation helpful? Give feedback.
All reactions