For Laravel 10 I suggest the following helper class (intl package required):
namespace App\Helpers;
use IntlDateFormatter;
class Date
{
/**
* Returns the locale defined at config/app.php
* @return string Locale defined at config/app.php
*/
public static function getAppLocale(): string
{
return config('app.locale');
}
/**
* Returns a date formated according the given locale.
*
* @param int $timestamp The date timestamp.
* @param string $locale The locale string (Ex: "pt_BR").
* If no locale is provided, it uses the app locale.
*/
public static function toLocaleFormat(int $timestamp, string $locale=null): string
{
if (empty($locale)) {
$locale = self::getAppLocale();
}
$formatter = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
if ($formatter === null) {
throw new \Exception(intl_get_error_message());
}
return $formatter->format($timestamp);
}
}
To format a date just use:
echo Date::formatLocale($timestamp);
To format a Carbon model attribute:
echo Date::formatLocale($model->column_name->timestamp);
Additionaly, you can create a model method to make easy date formating:
namespace App\Models;
use App\Helpers\Date;
class BaseModel extends Model
{
public function localDate(string $attribute): ?string
{
if ($this->{$attribute} === null) {
return null;
}
return Date::toLocaleFormat($this->{$attribute}->timestamp);
}
}
Extends BaseModel in your model classes and you can get locale formatted dates just calling:
{{ $model->localDate('column_name') }}