Search code examples
laravellaravel-resource

Laravel cast model values when using Resource


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 ?


Solution

  • 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'),