skip to Main Content

For formatting some date column via casts, for example:

protected $casts = [
    'deadline' => 'date:d/m/Y',
];

when getting column, it’ll return carbon instance:

dd($model->deadline);

// IlluminateSupportCarbon @1671235200 {#1542 ▶}

But even when it’s casted to string, it won’t be formatted as specified in cast:

dd( (string) $model->deadline );

// "2022-12-17 00:00:00"

Just when I can get formatted date, that whole model be casted toArray, or toJson,

dd($model->toArray()['deadline']);

// "17/12/2022"

So there isn’t any easier way to get formatted date without casting whole model?

2

Answers


  1. You can use a getter to overwrite your attribute :

    public function getDeadlineAttribute()
    {
        return $this->deadline->format('d/m/Y');
    }
    

    If you want all your date formated that way for your model, you can use this :

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('d/m/Y');
    }
    
    Login or Signup to reply.
  2. You can add to your model a new getter function like this:

    public function getFormatedDateAttribute()
    {
        return $this->deadline->format('d/m/Y');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search