Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve casted date without toArray or toJson?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading