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

Stratos's avatar
Level 14

Two different date mutators. Is it possible?

Let's assume I need to retrieve created_at formatted in two different ways, is this possible using mutators?

0 likes
7 replies
systematis's avatar

How would you specify which of the two formats you want?

systematis's avatar

Yes, it is possible. For example:

public function getFormattedCreatedAtAttribute()
{
    return $this->created_at->format('F j, Y');
}
Stratos's avatar
Level 14

Yeah, that is one format. But how would I do it if I needed two different formats?

systematis's avatar

Create another mutator with a slightly different name, e.g.

public function getCreatedAtOtherFormatAttribute()
{
    return $this->created_at->format('U');
}

Or set one of the two formats in the $dateFormat model property, and the other one in the mutator.

systematis's avatar

You could also create a general method:

public function createdAt(string $format)
{
    return $this->created_at->format($format);
}
Snapey's avatar

most would seem a little pointless as you can just add format() wherever you need to use it, e.g.

{{ created_at->format('U') }}

1 like
Stratos's avatar
Level 14

I cannot do that if I'm retrieving data through laravel api. I have to send the dates already converted.

Please or to participate in this conversation.