I'm using Laravel 10.10.1 and as title suggests, the serializeDate is not being called when using JsonResource, while the documentation clearly states that it will be. When I call the serialization directly, the serializeDate is called properly, ex.: $model->toArray().
Model.php:
protected $casts = [
'received_at' => 'datetime:d-m-Y H:i'
];
protected function serializeDate(DateTimeInterface $date): string
{
return $date->format('d-m-Y H:i');
}
ReadController.php:
public function __invoke(ReadRequest $request, Model $model): Resource
{
return new Resource($model);
}
Resource.php:
class Resource extends JsonResource
{
public function toArray($request): array
{
return [
'received_at' => $this->received_at,
];
}
}
Result:
received_at: "2023-07-22T09:46:00.000000Z"
Expected result:
received_at: "22-07-2023 09:46"
What am I doing wrong?
Please note that when I try one of these, it works properly:
But I do not want to use these, I want to use as I wrote above in ReadController.php. Is that even possible?
As said here
When defining a date or datetime cast, you may also specify the date's format. This format will be used when the model is serialized to an array or JSON
You can go with the below workaround:
class Resource extends JsonResource
{
public function toArray($request): array
{
$serializedData = $this->resource->toArray();
return [
'received_at' => $serializedData['received_at'],
];
}
}
with $this->resource, you can access the original model object and call toArray.
Also, the default JsonResource is the same.
public function toArray(Request $request)
{
if (is_null($this->resource)) {
return [];
}
return is_array($this->resource)
? $this->resource
: $this->resource->toArray();
}
If resource is not an array, then it will call toArray method on the resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With