Can not format datetime in laravel 7.2.2

Viewed 2571

i am currently working in laravel 7.2.2 and I am trying to format following datetime in to 'M d Y' .

"created_at": "2020-03-23T12:17:29.000000Z",

Previously, in laravel 6, datetime formats are like this: 2019-12-02 20:01:00. but now, date format is changed, and appearing like above: 2020-03-23T12:17:29.000000Z.

In laravel 6 i used to format my datetime as following code:

foreach ($posts as $post) {
        $createdAt = Carbon::parse($post['created_at']);
        $post['created_at'] = $createdAt->format('M d Y'); 
}

But it gives me same output as above 2020-03-23T12:17:29.000000Z . So, how can i format my datetime in laravel 7. Any help?

2 Answers

This was a breaking change introduced in Laravel 7.0. You can still format it the way you want.

You can override the serializeDate method on your model:

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface  $date
 * @return string
 */
 protected function serializeDate(DateTimeInterface $date)
 {
     return $date->format('M d Y');
 }

See the docs in the upgrade guide for more information.

HTH

You can use Eloquent resources to transform the data from your model to what the API should respond with. That way you won't need to touch the data and how the data is saved in your model.

It could look like something like this, given that your column names are the same:

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Request;

class Post extends JsonResource
{
    public function toArray(Request $request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'text' => $this->text,
            'created_at' => $this->created_at->format('M d Y'),
            'updated_at' => $this->updated_at->format('M d Y'),
        ];
    }
}
Related