Reputation: 185
In my Eloquent Model I have added a class attribute:
/**
* @return bool
*/
public function getIsViewable()
{
return $this->isViewable;
}
This attribute is not saved in the database as it is just a computed value.
In my controller I have an Eloquent Collection of this object which I convert to an array:
$images = $query->get();
$images = $images->toArray();
How can I add the class attribute property to each image item in the array?
Upvotes: 0
Views: 875
Reputation: 679
getMyVariableAttribute
ie. getIsViewableAttribute
protected $appends = ['is_viewable']
in order to get the computed property when serializing.Upvotes: 2
Reputation:
Your method name is missing the Attribute
part. Rename getIsViewable()
to getIsViewableAttribute()
/**
* @return bool
*/
public function getIsViewableAttribute()
{
return $this->isViewable;
}
https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
Upvotes: 1