Why is my Laravel Eloquent accessor not showing up in the response?

online Thomas picture online Thomas · Dec 18, 2017 · Viewed 11.2k times · Source

I have a Model Review that has a unix timestamp as 1 of it's attributes (table columns).

I use 2 accessors inside this model:

public function getReviewDateAttribute($value)
{
    return strftime('%A %e %B %Y', $value);
}

public function getReviewDateIsoAttribute()
{
    return Carbon::createFromTimestamp($this->review_date)->toDateTimeString();
}

getReviewDateAttribute works as expected and shows up in the collection of models when I write a query.

However getReviewDateIsoAttribute does not. What could be the reason for this?

A subquestion: If I use the same attribute in both functions, how can I use the original format as input value?

enter image description here

Answer

lagbox picture lagbox · Dec 18, 2017

You should be adding it to the $appends array. It isn't spinning through all available methods looking for getXXXXXAttribute. The other one is used because it is an accessor for an actual attribute, this one is not an actual attribute.

class YourModel ....
{
     protected $appends = ['review_date_iso'];
     ...
}

Laravel 5.5 Docs - Eloquent - Serialization - Appending Values to JSON