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

rutvik106's avatar

Dynamic date formats for Eloquent model

I want to convert some date fields into format defined by user. Those date formats are saved in database table. Below is the detailed explanation.

My application is having multiple projects, at the time of creating a project user specifies date format eg: 'd-m-Y', 'm-d-Y', 'Y-m-d' this date format gets saved into database. Now at the time of fetching any details regarding the project I want every date fields to be converted into the format specified by the user. Is there anyway to do this without using loops or custom queries?

0 likes
3 replies
Snapey's avatar

you should avoid setting the format in the stored record, and instead just set it when being displayed in a view.

eg, suppose the format is in user.dateformat, and you need to display eventdate

{{$eventdate->format($user->dateformat) }}

You could simplify this in the view with a custom blade tag.

Alternatively you could create accessors on your model that format the dates for users

public function getUserEventdateAttribute()
{
    return $this->eventdate->format(Auth::user()->dateformat);
}

in blade

{{ userEventdate }}
rutvik106's avatar

@snapey Yes you are right, And I too thought of the same. But then I have to make changes on many places and suppose I require Android/iOS app in future I have to make changes twice. Why it is not a good idea to format the dates in API itself? I want to do this in Lumen.

Snapey's avatar

Your API should send out all dates/times in UTC and let the client take care of localisation

Please or to participate in this conversation.