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?
How would you specify which of the two formats you want?
Yes, it is possible. For example:
public function getFormattedCreatedAtAttribute()
{
return $this->created_at->format('F j, Y');
}
Yeah, that is one format. But how would I do it if I needed two different formats?
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.
You could also create a general method:
public function createdAt(string $format)
{
return $this->created_at->format($format);
}
most would seem a little pointless as you can just add format() wherever you need to use it, e.g.
{{ created_at->format('U') }}
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.