devfaysal
devfaysal

Reputation: 168

Laravel blade does not respect date cast formatting

I have a birth date field in users table

$table->date('dob');

User model has Casts

protected $casts = [
        'dob' => 'date:d-m-Y'
    ];

In Blade,

{{$user->dob}}

I was expecting 26-11-2019 but found it shows 2019-11-26 00:00:00

Why I need to format the date again in blade when display?

What did I miss? Or what I was expecting, is not the purpose of formatting?

Upvotes: 2

Views: 1314

Answers (3)

kheengz
kheengz

Reputation: 1018

that will only work when you use a ->toArray() or ->toJson() on the object or collection in question, from the doc here https://laravel.com/docs/6.x/eloquent-mutators#date-casting

A way around that of you weren't using any of the above function call is to create an accessor or getter method in the model.

    use Carbon\Carbon; // import the Carbon lib.


    protected $dates = ['dob'];

    public function getDobAttribute($value)
    {
        return Carbon::createFromFormat('d-m-Y', $value);
    }

Upvotes: 0

Roman Meyer
Roman Meyer

Reputation: 2872

Date casting uses only for arrays or JSON, as explained here:

https://laravel.com/docs/6.x/eloquent-mutators#date-casting

You can try to do it via mutator:

https://laravel.com/docs/6.x/eloquent-mutators#date-mutators

protected $dates = [
    'dob', // it will be 'Y-m-d H:i:s'
];

protected $dateFormat = 'd-m-Y'; // but you can redefine it

Upvotes: 2

Tim Lewis
Tim Lewis

Reputation: 29278

protected $casts = [...] tells Laravel to treat the properties as Carbon instances, but you still need to format them:

{{ $user->dob->format('d-m-Y') }}

As far as I'm aware, there isn't a way to output a default format, unless you use an accessor:

In your User.php model:

public function getDobFormattedAttribute(){
  return $this->dob->format('y-m-D');
}

Then in your view:

{{ $user->dob_formatted }}

Upvotes: 4

Related Questions