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

vincent15000's avatar

Date casting format seems to not work

Hello,

I probably do womething wrong, but what ?

protected $casts = [
    'start_date' => 'date:Y-m-d',
    'end_date' => 'date',
];

With this code, the date should display 2024-03-11, shouldn't it ?

{{ $model->start_date }}

But I get 2024-03-11 00:00:00 instead of 2024-03-11.

What am I doing wrong ?

Thanks for your help.

V

0 likes
9 replies
Ssionn's avatar

From what I know, you can't format in the cast. You'll have to format it in your blade templating:

protected $casts = [
    'start_date' => 'date',
    'end_date' => 'date',
];
{{ $model->start_date->format('Y-m-d') }}

Edit: Just realized that yours does work for storage and retrieval purposes but you still have to format it properly

1 like
Ssionn's avatar

@vincent15000 What is it exactly that you're trying to achieve? I'm not understanding properly

1 like
gych's avatar

Try to use datetime in your casts instead of date

'start_date' => 'datetime:Y-m-d',
1 like
aknEvrnky's avatar

you may write your own accessor mutator,

use App\Support\Address;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Casts\Attribute;
 
protected function startDate(): Attribute
{
    return Attribute::make(
        get: fn (mixed $value, array $attributes) => Carbon::parse($value)->format('Y-m-d'),
    );
}
1 like
Snapey's avatar

@aknEvrnky You don't need to carbon parse something that is already a carbon instance.

3 likes
Snapey's avatar
Snapey
Best Answer
Level 122

Yes but this is a problem to fill an input date (not datetime).

Why?

<input type="date" value="{{ old('start_date', $model->start_date->format('Y-m-d')) }}" name="start_date" />
1 like
vincent15000's avatar

@Snapey Thank you ;) this seems to be the best approach for me, I use this code directly in the livewire form to initialize the property and it works fine.

Please or to participate in this conversation.