I believe when you use the protected $dates array, Laravel automatically has and calls an accessor to convert the date string to a Carbon object so the mutator in your view won't get called.
I'm not too sure but I believe so.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi all,
I'm trying to figure out the best way to manage (get & set) dates in my app. The protected $dates array is a great tool. It automatically converts a date string to a Carbon object, and it makes storing the dates easy and uniform (I use mutators).
protected $dates = ['birth_date'];
I can now echo a date in my view like this:
{{ $user->birth_date->format(config('view.date_format')) }}
That's ok, but kinda redundant. It means I have to do this in every view, for every date attribute (I have a lot of 'em). So I was checking out the accessors. I assumed I could simply create an accessor:
public function getBirthDateAttribute($date) {
return $date->format(config('view.date_format'));
}
and then in my view:
{{ $user->birth_date }}
and get a nicely formatted date. But this isn't working. The $date is still a simple string at this moment. It seems that it's only converted to a Carbon object after the accessor is called. My conclusion is that the accessors don't make sense in combination with the $dates array and I'll have to format each Carbon object manually in my views.
Am I right?
EDIT: as it turns out, in my case, I don't need the $dates array. I seems that I just need to define an accessor and a mutator:
public function getBirthDateAttribute( $date )
{
$date = Carbon::createFromFormat(config('view.def_date_format'), $date);
return $date->format(config('view.date_format'));
}
public function setBirthDateAttribute( $date )
{
$this->attributes['birth_date'] = Carbon::createFromFormat( config( 'view.date_format' ),
$date );
}
, and everything works as it should. Don't hesitate to share your view though, if you see it differently.
Please or to participate in this conversation.