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

azamtav's avatar

Define a default date format that can still be changed later?

Is there a best practice if I want to define a default presentation format for all my model's dates. 90% of the time I would probably use this same formatter, but every now and again I may want to display it different. Do I need to define a mutator on each model, does Carbon dates allow for a default format, what is the best way to do this? The point is to save time on having to define this format all over the place. However, maybe this is a bad practice to try and default it...

My default format would be:

$myDate->format('m/d/Y');

The point of this would be in my blade views I can simply just say output $myDate and not have to worry about remembering the formatter.

0 likes
1 reply
Amaury's avatar

@azamtav it is better to keep the Carbon format since it allows comparisons very easily, to have a format readable for humans.

In a model you can add a new attribute:

If the column name is "date" and date is casted as Carbon, you can add in your model:

use Illuminate\Database\Eloquent\Casts\Attribute;
/**
 * Get the "date" attribute formatted as m/d/Y.
 */
public function dateFormatted(): Attribute
{
    return Attribute::get(fn () => $this->date->format('m/d/Y')); // adapt with the column name…
}

And know the "date_formatted" attribute will display the good format:

$myInstance->date_formatted; // String format '04/27/2024'

Please or to participate in this conversation.