Search code examples
phplaravellaravel-bladephp-carbon

Wrong locale for dates in Laravel app in production on Heroku


I have an issue with dates locale in my Laravel App hosted on Heroku.

In the blade files I show the dates value like this:

{{ $user->dateBirth? Carbon\Carbon::parse($user->dateBirth)->formatLocalized('%d/%b/%Y') : ''}}

I have set the locale in AppServiceProvider:

public function boot(Charts $charts){
     Carbon::setLocale('it');
     setlocale(LC_TIME, 'it_IT', 'it', 'IT', 'Italian', 'it_IT.UTF-8');
}

I want to show the month in IT locale, like 23/Gen/2021, on my localhost this works fine, but in production on Heroku the value showed is 23/Jan/2021.

How can i solve it?


Solution

  • It simply means Heroku does not have it locale installed on the OS so LC_TIME won't work and formatLocalized neither. Hopefully, Carbon has its own translations with even more formats supported than formatLocalized (which actually rely on OS locales installed). See ->isoFormat() in https://carbon.nesbot.com/docs/#api-localization

    {{ $user->dateBirth ? Carbon\Carbon::parse($user->dateBirth)->isoFormat('DD/MMM/YYYY') : ''}}
    

    My recommandation is to always use ->isoFormat() so your code works on any machine with no extra install/setting, and those can be customized so you can change the Carbon translations without impacting the rest.