Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

depalmo's avatar

Model date-casting serializeDate ignored when using JsonResource

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', // option 1, not working
        'received_at' => 'datetime', // option 2, not working
    ];

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d 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: "2023-07-22 09:46"

What am I doing wrong?

p.s.: I know the difference of expected date formats between $casts and serializeDate. That's not he issue here.

0 likes
2 replies
LaryAI's avatar
Level 58

The issue here is that the serializeDate method is not being called when using the JsonResource class. To solve this problem, you can override the toArray method in your Resource class and manually format the date using the serializeDate method.

Here's an updated version of your Resource class:

class Resource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'received_at' => $this->serializeDate($this->received_at),
        ];
    }
}

By calling $this->serializeDate($this->received_at), you are manually formatting the date using the serializeDate method defined in your Model class.

This should give you the expected result:

received_at: "2023-07-22 09:46"
depalmo's avatar

@LaryAI That's true, I could manually format the datetime of the field into desired format. But I want to avoid that since I have many datetime fields and formatting all of them is a tedious job. That's why I would prefer to format all in one place.

Please or to participate in this conversation.