Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mindz's avatar
Level 10

getAttribute in laravel 5.5

Is something has been changed?

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

0 likes
3 replies
lostdreamer_nl's avatar

Hmmm, no nothing in this flow has changed.

Illuminate\Database\Eloquent\Model.php line 1260

    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.

mindz's avatar
Level 10

I have tried this on so many ways

  • ->relation()-first()
  • ->relation
  • ->find
  • ->where()->get()->first()

and sooo on.... and there is something wrong with it

this function works like a charm in all above ways

 public function getFieldAttribute($value)
{
        return someFunction($value);
}
    

this never works

public function getAttribute($key)
{
        $value = parent::getAttribute($key);

        return someFunction($value);
}
  

Does someone encounter this problem before?

mindz's avatar
mindz
OP
Best Answer
Level 10

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;
}

Please or to participate in this conversation.