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.
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']]);
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community