Different date accessors in same Model

325 views Asked by At

I have this, and it works nicely to give me UK-formatted dates:

protected $dateFormat = 'd-m-Y';
protected $dates = ['purchased', 'warranty_expires', 'scrapped_on', 'location_date', 'user_date'];

However, I also have created and modified (not the standard Laravel ones, but my own) that are Timestamps, not dates. How can I automate the formatting of those two fields when they are retrieved, to something like 'd-m-Y H:i:s' ?

2

There are 2 answers

0
Nazmul Hasan On BEST ANSWER

You can do this with Carbon library

public function getFormattedPurchasedAttribute($date)
{
   return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d-m-Y H:i:s');
}

You have to use carbon class. Write this line in the top where all namespace are used.

use Carbon;
3
Marcin Nabiałek On

I personally don't use $dateFormat attribute because it changes format for all dates fields. What I would do is creating custom accessors to get formatted fields for example:

public function getFormattedPurchasedAttribute($value) {
  return $this->asDateTime($value)->format('d-m-Y H:i:s');
}

so you can now use $model-formatted_purchased to get purchased field formatted in way you want