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

JeroenVanOort's avatar

Default Carbon format

I'm making a REST API and would like to display all dates in a format that includes the timezone. Where can I change the default format for Carbon?

I know I could add accessors for every date in all my models, but I don't think that's the best way to go.

Jeroen

0 likes
7 replies
JarekTkaczyk's avatar
Level 53

@JeroenVanOort call this at startup:

Carbon::setToStringFormat('your format');

But be careful and don't pass carbon object somewhere as a model attribute (eg. in custom mutator) and try to save, because it would be a problem ;)

2 likes
JeroenVanOort's avatar

Thanks. I placed it in bootstrap/app.php as Carbon\Carbon::setToStringFormat('c'); and it does the trick!

1 like
JeroenVanOort's avatar

This doesn't seem to work anymore. It might have to do with Laravel 5.1, but I can't seem to find out what's going wrong. The call in bootstrap/app.php simply doesn't change anything; it's back to the Laravel defaults.

Any help is very much appreciated!

JadoJodo's avatar

I was able to get a workaround for this by creating a few mutators on an intermediate abstract class (ModelA extends ModelB) called:


abstract class ModelB extends Model 
{
   /**
     * Converts the created_at to Atom-format
     *
     * @return string
     */
    public function getCreatedAtAtomAttribute()
    {
        return $this->created_at->toAtomString();
    }

    /**
     * Converts the updated_at to Atom-format
     *
     * @return string
     */
    public function getUpdatedAtAtomAttribute()
    {
        return $this->updated_at->toAtomString();
    }
}

This allows you to call $modelA->created_at_atom (or something similar) and maintains the created_at attribute as it works currently.

1 like
omidgfx's avatar

It's deprecated now! What should we do? I need it for my entire APIs which I'm designing.

hupp's avatar

@jeroenvanoort Try this might get very helpful.

  • app/Providers/AppServiceProvider.php
use Illuminate\Support\Carbon;

public function boot()
{
    Carbon::serializeUsing(function ($carbon) {
        return $carbon->format('Y-m-d H:i:s e'); // Customize the format as per your requirements
    });
}

This will set the default date format for Carbon whenever it is serialized, including when your models are converted to JSON in the context of a REST API response.

Please or to participate in this conversation.