The problem lies with the $this->sites. It is correct that it will throw an exception that you class instance does not have a property $sites.
Take a look at the __get method of Model. You can see here that a getAttribute($key) call is being made. Diving even deeper you would find out that at some point the following code is being executed in the transformModelValue method:
if ($this->hasGetMutator($key)) {
return $this->mutateAttribute($key, $value);
}
This piece of code calls your getSitesAttribute method.
Going back a little bit and you will see that it tries to retrieve the value for the $key (sites) from the attributes array by calling the getAttributeFromArray($key). This will return the value stored in the attributes array which is where your setSitesAttribute mutator stores the value.
The following options I could come up with:
- Remove the accessor to let the model retrieve the value from the
$attributes array.
protected $appends = ['sites'];
public function setSitesAttribute($value)
{
$this->attributes['sites'] = $value;
}
- Store value in and retrieve from
$sites property. Not sure if $appends still works.
protected $appends = ['sites'];
private $sites = [];
public function getSitesAttribute()
{
return $this->sites;
}
public function setSitesAttribute($value)
{
$this->sites = $value;
}
public function getSitesAttribute(){ dd($this->attributes['sites']); }