Search code examples
phplaravellaravel-5

Modify all attributes of a Laravel model


Accessors will do their job on a single attribute perfectly, but I need a way to have a method to do an Accessor/Getter job on all attributes and automatically.

The purpose is that I want to replace some characters/numbers on getting attributes and then printing them out. I can do it from within controller and manually but I think it would be great to have it from model side and automatically.

Like overriding getAttributes() method:

public function getAttributes()
{
    foreach ($this->attributes as $key => $value) {
        $this->attributes[$key] = str_replace([...], [...], $value);
    }
    return $this->attributes;
}

But I have to call it every time on model $model->getAttributes();

Any way to do it automatically and DRY?


Solution

  • Try something like:

    public function getAttribute($key)
    {
        if (array_key_exists($key, $this->attributes) || $this->hasGetMutator($key)) {
            if($key === 'name') return 'modify this value';
            return $this->getAttributeValue($key);
        }
    
        return $this->getRelationValue($key);
    }
    

    It's fully overriding the default method so be a bit careful.

    EDIT

    Also check out: http://laravel.com/docs/5.1/eloquent-mutators