Home > OS >  timestamp column is not in ISO 8601 format
timestamp column is not in ISO 8601 format

Time:11-17

I want all the dates from the server to be sent in the ISO 8601 standard in Laravel. Laravel version is 9. The created_at and updated_at columns are sent in the wanted format but my custom column is not in that format.

Here is the code of the Seeder

"questions_updated_at" => Carbon::now()->format('Y-m-d H:i:s'),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
"updated_at" => Carbon::now()->format('Y-m-d H:i:s')

Also tested with now() In MySQL their values are same. Migration

$table->timestamp("questions_updated_at");
$table->timestamps();

In the Model. protected $dateFormat = \DateTime::ISO8601;

In Controller return response(MyClass::where('show_on_front', true)->get());

And in Postman getting it like this.

[{
   "questions_updated_at": "2022-11-16 15:02:44",
   "created_at": "2022-11-16T15:02:44.000000Z",
   "updated_at": "2022-11-16T15:02:44.000000Z"
}]

In app.php the time zone is 'timezone' => 'UTC' Help will be appreciated.

CodePudding user response:

You have to use casts in order to change the type of the data fetched from the data,

in the model file

protected $casts = [
   'questions_updated_at' => 'datetime',
];

the timestamp is stored as timestamp and it is fetched as string from database , casts is used to change it to the prefered DateTime format , the created_at and updated_at are already casted in HasAtttributes trait

  • Related