Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 1 year ago.
0
Solution

Laravel stores model attributes in $model->attributes and not what you actually see such as $this->name.

The accessors and mutators are called through PHPs magic __call, __get and __set methods, these magic methods are only triggered when a property doesn't exist on the object or you don't have the correct scope when accessing (i.e: attempting to access a protected property of a parent class from the child class)

So if you declare $name on the object, the magic method __get will not be called and thus the accessor will not be called and you'll just get the actual objects property.

A way around this would be to store your own properties in $model->custom_attributes and do similar to your code above.

public function getNameAttribute()
{
    if (isset($this->custom_attributes['name']))
    {
        return $this->custom_attributes['name'];
    }

    return implode(' ', [$this->first_name, $this->last_name]);
}

You could also extend the Eloquent model and add your own logic into the magic functions. Have a look through the API to see how Laravel does it and that'll give you a better understanding of how to do that.

Last updated 1 year ago.
0

Thanks very much, i do it this way

public function getNameAttribute()
{
	if( isset($this->attributes['name']) and $this->attributes['name'])
	{
		return $this->attributes['name'];
	}

	return implode(' ', [$this->attributes['first_name'], $this->attributes['last_name']]);
}
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mejlo mejlo Joined 27 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.