2

I have a created_at column in my user model that I would like to format differently when accessing it in my blade template, so it is more readable. It seems like the best way to go about this is to use a cast.

I created a cast like so:

     protected $casts = [
        'email_verified_at' => 'datetime',
        'created_at'  => 'm-d-y',
    ];

... in my controller, I am getting a User and then doing:

dd($member->toArray());

Now, when getting a user record and doing $user->toArray() the created_at column is still in the original uncasted format, it seems the cast isn't being used at all, any idea why this is?

AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • I don't think `m-d-y` is valid in `$casts`, since casting it for setting type, like `string`, `int`, `datetime`, etc, not for formatting. – Tim Lewis Apr 10 '20 at 16:56
  • https://stackoverflow.com/questions/24441395/how-to-change-default-format-at-created-at-and-updated-at-value-laravel –  Apr 10 '20 at 17:06

1 Answers1

5

You can define a format for date columns using following snippet(in model):

protected $dateFormat = 'm-d-Y';

In case of updating individual timestamp fields use the following.

protected $casts = [
    'created_at'  => 'date:m-d-Y',
    // 'updated_at' => 'datetime:Y-m-d H:00',
];
Sachin Kumar
  • 3,001
  • 1
  • 22
  • 47