Home > Net >  How to retrieve casted date without toArray or toJson?
How to retrieve casted date without toArray or toJson?

Time:01-31

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);

// Illuminate\Support\Carbon @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?

CodePudding user response:

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');
}

CodePudding user response:

You can add to your model a new getter function like this:

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