mathnabit
mathnabit

Reputation: 360

How to change format of created_at and updated_at in laravel Model?

In laravel response I want to get values of "created_at" and 'updated_at" like this format (without seconds):

2022-02-22 04:07

I try to use :

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

But not works, the datetime stills in default format.

Upvotes: 2

Views: 8556

Answers (2)

Bhola Kr. Khawas
Bhola Kr. Khawas

Reputation: 385

If your 'created_at' and 'updated_at' fields are date time object or carbon instance you can simply do

 public function getCreatedAtAttribute($date)
  {
    return  $date->format('Y-m-d H:i');
 }

 public function getUpdatedAtAttribute($date)
 {
   return $date->format('Y-m-d H:i');
 }

if its neither date time object nor carbon instance you need to either convert your string to date time instance as @gguney answered .

You can also define the field inside

protected $dates  = [ 'created_at' , 'updated_at'];

Note : The formatted values only reflect while you print the data or dump if the field is inside some array or collection you cannot see the format as these method will be called just before printing the specific field.

Upvotes: 3

gguney
gguney

Reputation: 2643

You can use something like this:

public function getCreatedAtAttribute($date)
{
    return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d H:i');
}

public function getUpdatedAtAttribute($date)
{
    return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d H:i');
}

use these

Upvotes: 4

Related Questions