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

musilondrej's avatar

Seeking alternative to deprecated code for globally setting Carbon formatting in Laravel

Hello everyone,

I have been using Laravel's Carbon library in my application for date and time formatting. Currently, I have the following code in my AppServiceProvider.php file to globally set the formatting by user preferences.

Carbon::serializeUsing(function (Carbon $carbon): string {
    $user = auth()->user();
    return $carbon->format($user->date_format . ' ' . $user->time_format);
});

However, I recently discovered that this code is deprecated and I'm searching for an alternative solution to address this issue. I want to be able to globally set the formatting for the Carbon library.

If anyone has any suggestions or knows the updated approach to achieve this, I would greatly appreciate your help.

Thank you in advance!

0 likes
1 reply
martinbean's avatar
Level 80

@musilondrej I’d invert turn things around to be honest.

If you want to get a date and time, formatted using the user’s preference, then I’d make the User model responsible for that:

public function formattedDateTime(Carbon $dateTime): string
{
    return $dateTime->format($this->date_format . ' ' . $user->time_format);
}
echo $user->formattedDateTime($someCarbonInstance);
1 like

Please or to participate in this conversation.