AnchovyLegend
AnchovyLegend

Reputation: 12538

Laravel cast for created_at date field not being applied

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?

Upvotes: 2

Views: 5141

Answers (1)

Sachin Kumar
Sachin Kumar

Reputation: 3240

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',
];

Upvotes: 5

Related Questions