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

Elodis's avatar

Extend on a Carbon date instance?

Hello all-

In my app, I'm frequently writing:

$model->created_at->formatLocalized(Config::get('local.dateFormat'))

$model->updated_at->formatLocalized(Config::get('local.dateFormat') . ' %H:%M:%S')

On all sorts of dates. The idea is to be able to configure several date formats into one config file to change throughout the system.

Is there a way to extend the Carbon instance so that I could do something like:

$model->created_at->formatted();

$model->updated_at->formattedWithTime();

Instead?

Thanks,

Matt

0 likes
5 replies
jekinney's avatar

Few ways. Helper class or attributes in a model.

JarekTkaczyk's avatar

@Elodis No, you can't extend Carbon, since it doesn't let you do so.

But you can do this in your models using mutators and accessors.

Elodis's avatar

Well I thought presenters would work, but that's on a model by model basis.

Is there a way I can set a presenter on any Carbon date defined by any getDates()

jijoel's avatar

I've been working on a class to do exactly that. It's the FormattedCarbon object at https://github.com/kumuwai/date-range.

You can output a formatted string by doing things like this:

$this->created_at->short
$this->created_at->time
$this->created_at->style("something")

If you want it to apply globally, extend your models from a BaseModel class (which extends Eloquent), and override the asDateTime() method.

Please or to participate in this conversation.