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

ivanhalen's avatar

Best way to repeatly format a date in my language (italian)

Hello, I am new to Laravel and OOP in general, trying to switch from old procedural code. I'd like to show some dates coming from my Models in my language (italian) for readability reasons: so far, that's what I did:

  1. change 'locale' => 'it' in config/app.php file
  2. put setlocale(LC_TIME, config('app.locale')); in routes.php file, see also my previous question
  3. put protected $dates = ['published_at', 'expires_at']; in my Model(s) to leverage Carbon
  4. put {{ utf8_encode($record->published_at->formatLocalized('%A %d %B %Y')) }} in my Blade view(s)

(NOTE: I MUST use utf8_encode(), otherwise dates with accented letters (lunedì, martedì, etc.) don't show up: don't know why and can't find the answer googling... is there a reason for this? Is it a Laravel or Carbon bug?)

My question is about the last point: writing that long {{ utf8_encode($record->published_at->formatLocalized('%A %d %B %Y')) }} piece of code every time is tedious and it would be faster (and reusable) to write {{ formatItalian($record->published_at) }}

What's the best way to accomplish this? I read about the custom helpers functions, would this be a good approach? As I said, I'm new to Laravel switching from procedural code, and trying to use the best practices, so sorry for the dumb question... Thanks

0 likes
5 replies
bestmomo's avatar

You can use a presenter. Here is an example :

<?php namespace App\Presenters;

use Carbon\Carbon;

trait DatePresenter {

    /**
     * Format created_at attribute
     *
     * @param Carbon  $date
     * @return string
     */
    public function getCreatedAtAttribute($date)
    {
        return $this->getDateFormated($date);
    }

    /**
     * Format updated_at attribute
     *
     * @param Carbon  $date
     * @return string
     */
    public function getUpdatedAtAttribute($date)
    {
        return $this->getDateFormated($date);
    }

    /**
     * Format date
     *
     * @param Carbon  $date
     * @return string
     */
    private function getDateFormated($date)
    {
        return Carbon::parse($date)->format(config('app.locale') == 'fr' ? 'd/m/Y' : 'm/d/Y');
    }

}

And use it in model :

use App\Presenters\DatePresenter;

class Post extends Model  {

    use DatePresenter;
ivanhalen's avatar

@ohffs: I read about accessors, but if I'm not wrong this is "per Model" and I need to format dates on many models (news, posts, users logs, etc): that would repeat my code

@bestmomo: this seems nice, but I couldn't find any reference to "presenters" in docs... please can you link me if you have any official reference? Thanks both anyway!!! :-)

Please or to participate in this conversation.