Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Resource gives object instead of value of date format

Tags:

laravel

I'm using laravel resource to send my api

class OfferResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'created_at' => $this->created_at,
        ];
    }
}

This gives me (on laravel 5.6) an object:

created_at: {
    date: "2018-05-10 18:49:15.000000",
    timezone: "UTC",
    timezone_type: 3
}

This is unexpected, beacause on laravel 5.5 I had raw date. However I tried to make protected casts, as mentioned in official documentation:

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

and this is not working at all.

like image 833
gileneusz Avatar asked May 10 '18 19:05

gileneusz


1 Answers

You may try something like this:

public function toArray($request)
{
    return [
        'created_at' => $this->created_at->format('Y-m-d H:i:s')
    ];
}
like image 133
The Alpha Avatar answered Nov 15 '22 10:11

The Alpha