is it the same if you use $this->attributes['created_at'] ?
Feb 3, 2017
7
Level 1
Use created_at in accessor in Laravel 5.3?
Hi. I'm trying to use created_at in a model accessor method in Laravel 5.3, and I can't get it to work. Basically I am trying to create an appended property called 'age_days' using an accessor method called 'getAgeDaysAttribute()' that returns the age of the model in days since the 'created_at' date. But when I try to use 'created_at' in an accessor it is always null. Here is an example of the code I have tried.
/*
* Pseudo-fields that get added to the models when the models are exported to json.
*/
protected $appends = ['age_days'];
/*
* Returns age of model in days since created_at.
*/
public function getAgeDaysAttribute() {
return $this->created_at->diffInDays();
// return Carbon::createFromFormat('Y-m-d H:i:s', $this->created_at)->diffInDays();
}
Oddly, the code above works for date fields OTHER THAN created_at. For example, the following code works:
/*
* Pseudo-fields that get added to the models when the models are exported to json.
*/
protected $appends = ['age_days'];
/*
* Returns age of model in days since created_at.
*/
public function getAgeDaysAttribute() {
// note: using 'received_at' field rather than 'created_at' - this works
return Carbon::createFromFormat('Y-m-d H:i:s', $this->received_at)->diffInDays();
}
Please or to participate in this conversation.