Slimane MEHARZI
Slimane MEHARZI

Reputation: 364

Mutiple Mutators in Laravel Eloquent Model

To define a Mutator in a Eloquent Model class, we use the getFooAttribute like:

public function getTitleAttribute($value)
{
    return ucfirst($value);
}

But imagine that i have a lot (20 to 30) attributes in one Model that i'd like to rename, it's fastidious to create a function for each one, is there any smarter way to resolve this?

Upvotes: 0

Views: 58

Answers (1)

Jerodev
Jerodev

Reputation: 33186

You could override the getAttribute function on your model and have an associative array in there to rename the attributes.

public function getAttribute($key)
{
    $renames = [
        'foo' => 'bar',
    ];

    if (array_key_exists($key, $renames))
        $key = $renames[$key];

    return parent::getAttribute($key);
}

Upvotes: 1

Related Questions