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

javineo's avatar

Date format in the view. Laravel 5.5

I need to show the date extracted from a database from a model in a controller and sent to the view. The format that is given to me is the following: "2018-02-02 00: 00: 00.000". And I need it to look like this: "02/02/2018". I do not want to use hard code in the view.

Total Thanks!

0 likes
5 replies
tykus's avatar

If it is not already a Carbon instance, convert it on the model using the $dates property. Once it is a Carbon instance, then in your view:

{{ $date->format('d/m/Y') }}
javineo's avatar

This is my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Casos extends Model
{
        /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'casos';

    public $timestamps = false;

}
tykus's avatar

Depending on the name of the date field you are displaying, you will need to adjust as required - I will use date as a generic example:

class Casos extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'casos';
    public $timestamps = false;

    protected $dates = ['date'];
}

This will cast the property named date to a Carbon instance, so you can use the format method in the view.

Another option is to format the date in the model for presentation:

class Casos extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'casos';
    public $timestamps = false;

    public function getFormattedDateAttribute()
    {
        return Carbon::parse($this->date)->format('d/m/Y');
    }
}

This will make available a property called formatted_date on the model, which you can use in your view. Many would frown at incorporating presentation logic into your model; but, if it is used sparingly and you are conscious not to over-use this technique, then it is okay.

tykus's avatar

So, say you pass a $casos model instance to the view, then the formatted_date property would be displayed as follows:

{{ $casos->formatted_date }}

Please or to participate in this conversation.