Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abkrim's avatar
Level 13

Cast date attribute on model property not work?

I've a two datetime columns in Users, deleted_at & suspended_at and I like cast to date in format 'd/m/Y'

In code one use accessor/mutator pattern and other model caster property.

If use model caster propierty not work

User

protected $casts = [
    'deleted_at' => 'date:d/m/Y',
    'suspended_at' => 'date:d/m/Y',
    'is_admin' => 'boolean'
];

...
public function getSuspendedAtForHumansAttribute()
{
    return $this->suspended_at->format('d/m/Y');
}

Blade

<x-table.cell>
    @if ($user->suspended_at)
        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-{{ $user->status_color }}-100 text-{{ $user->status_color }}-800">
        {{ $user->suspended_at_for_humans }}
    </span>
    @endif
</x-table.cell>
<x-table.cell>
    @if ($user->deleted_at)
        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-{{ $user->status_color }}-100 text-{{ $user->status_color }}-800">
        {{ $user->deleted_at }}
    </span>
    @endif
</x-table.cell>

Image

0 likes
4 replies
Nakov's avatar

@abkrim have you tried datetime since the deleted_at field is a datetime type, and as the docs say:

'deleted_at' => 'datetime:d/m/Y',

https://laravel.com/docs/master/eloquent-mutators#date-casting

And the docs say this as well

When defining a date or datetime cast, you may also specify the date's format. This format will be used when the model is serialized to an array or JSON.

Note the last part, only when serialized to array or JSON.

abkrim's avatar
Level 13

Not work. I've tried already.

protected $casts = [
    'deleted_at' => 'datetime:d/m/Y',
    'suspended_at' => 'datetime:d/m/Y',
    'is_admin' => 'boolean'
];

I get same result. Of course delete caches, log out,...

Snapey's avatar

your cast is only used when the object is converted to an array or json

You need to use an accessor if you want object property to appear in another format

abkrim's avatar
Level 13

Hi.

I read this on Screencast Update: Add "$appends" for wire:model binding to model accessors

My english is so bad, and maybe I'm wrong for that.

Alternatively, now that Livewire now supports model casters for model properties, you can actually cast the >date field itself and avoid the accessor/mutator pattern all-together:

protected $casts => ['date' => 'date:m/d/Y'];

And now replace any date_for_editing references to just date and everything should work nicely.

Please or to participate in this conversation.