in trait i created for eloquent model i can't use getAttribute($key) - it is completly skipped . However setAttibute($key, $value) works like charm
trait SomeTrait
{
public function getAttribute($key)
{
return "it just not working";
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->specialPropertyArray)) {
return parent::setAttribute($key, someFunctionOn($value));
}
return parent::setAttribute($key, $value);
}
}
In addition i have to say i have no custom accessors for my models
public function __get($key)
{
return $this->getAttribute($key);
}
The magic get function will use getAttribute to get any key that doesnt exist as a public property on the model itself.
So unless the attribute you're trying to get from the model is also in a public var, or you have a custom magic __get method in your model, this should simply work.
For anyone who one day will be looking for an answer.Method getAttribute() is fired only when you call property like $model->property. If you returning collection which later is converted to array method that is used to do this is toArray() so to my Trait i had to add this method
public function toArray()
{
$array = parent::toArray();
foreach ($array as $key => $attribute) {
if (in_array($key, $this->specialPropertyArray)) {
$array[$key] = someFunction($attribute);
}
}
return $array;
}