Shaun
Shaun

Reputation: 185

Laravel - add a class attribute to array

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

Answers (2)

zjbarg
zjbarg

Reputation: 679

  1. Method should be named getMyVariableAttribute ie. getIsViewableAttribute
  2. On the model add the following protected $appends = ['is_viewable'] in order to get the computed property when serializing.

Upvotes: 2

user8034901
user8034901

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

Related Questions