Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

This is not a good practice to get into. You are essentially going to blow away the carbon instance just to display a specific format when instead you should be rendering said format when it's displayed in the view. You want to keep carbon as it allows you the flexibility to do just that, convert on the fly whenever you want. That said. your accessor way is definately the cleanest. This thread shows a way to do what you want, but somebody in the thread says it no longer works in 5.1

https://laracasts.com/discuss/channels/general-discussion/default-carbon-format

but again. recommend against it.

0

sotonin said:

This is not a good practice to get into. You are essentially going to blow away the carbon instance just to display a specific format when instead you should be rendering said format when it's displayed in the view. You want to keep carbon as it allows you the flexibility to do just that, convert on the fly whenever you want. That said. your accessor way is definately the cleanest. This thread shows a way to do what you want, but somebody in the thread says it no longer works in 5.1

https://laracasts.com/discuss/channels/general-discussion/default-carbon-format

but again. recommend against it.

Thanks for the reply!

I looked at the link you gave and Carbon::setToStringFormat('your format'); doesn't work. I think it's because of this bit of code in the base Model class which is chosing the format:

/**
     * Prepare a date for array / JSON serialization.
     *
     * @param  \DateTime  $date
     * @return string
     */
    protected function serializeDate(DateTime $date)
    {
        return $date->format($this->getDateFormat());
    }

(although I'm not 100% certain)

The accessor way may be clean but I don't want to write 50-100 of them. I could miss some, or forget to add it for new models. And losing the Carbon object really is a big disadvantage.

I'm building an API, so there isn't really a view for the data or I might agree that this is straying slightly from pure MVC. Even so, if I could change the serialization format just for display I wouldn't be losing the Carbon object, which means if I pass the object to a view later it wouldn't know the difference in the first place.

Unless there's something else I'm missing it looks like I'll have to extend the base Model class and override some of the serialization methods with my own.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.