Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel serializeDate ignored when using JsonResource

Tags:

laravel

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:

  • new Resource($report) (as printout of dd())
  • response($report->toJson())
  • response($report->toArray())
  • response($report)

But I do not want to use these, I want to use as I wrote above in ReadController.php. Is that even possible?

like image 393
Kristjan O. Avatar asked Mar 09 '26 17:03

Kristjan O.


1 Answers

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.

like image 123
AmooAti Avatar answered Mar 12 '26 16:03

AmooAti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!