0

When returning a model using resource created_at and updated_at casting is working fine, but when i modify the toArray() function the casting is not working !

in my model :

protected $casts = [
    'created_at' => 'datetime:Y-m-d:h',
    'updated_at' => 'datetime:Y-m-d:h',
];

in resource :

 public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'value' => $this->value,
        'box' =>  new BoxResource($this->box),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

in controller :

  public function index(Request $request)
{

    return CurrencyResource::collection(
        Currency::where("user_id", "=", $request->user()->id)
          
            ->paginate($per_page)
    );
}

How to make the casting work ?

derar sattouf
  • 69
  • 2
  • 9

1 Answers1

2

By it not working, you mean the timestamps revert to carbon instances? You could just use the format method then.

'created_at' => $this->created_at->format('Y-m-d:h'),
'updated_at' => $this->updated_at->format('Y-m-d:h'),
IGP
  • 14,160
  • 4
  • 26
  • 43
  • 1
    good answer but is there is any way to fix this globaly – derar sattouf Feb 15 '21 at 22:55
  • The documentation is clear on the subject of date casting using the `$cast`. "This format will be used when the model is serialized to an array or JSON:" – IGP Feb 15 '21 at 23:35