How to append property with Accessors in Eloquent

Sometimes, we need to add more property to the Model or transform the original Model. We can define our own custom fields on top of existing in the database table. But, there is an Eloquent property name $appends to help us done this quickly.

I assume our User Model has these fields.

User Table

Since we only have one field to hold the full name. In this case, it names name. But in other contexts, we need to separate the full name down to the first name and the last name. Here $appends property comes to help.

We define the extent fields that we want to return them in $appends property of User Model.

class User extends Model
...
	protected $appends = [
		'first_name',
		'last_name'
	];
...
}

Then, we define the related methods which return its value.

public function getFirstNameAttribute()

The name of the method adhere to this rule: get{camel_case_property_name}Attribute

For example: If our extent field name first_name so the name of method should be getFirstNameAttribute

Finally, we return the new value for new property in this method.

	public function getFirstNameAttribute()
	{
		if ( $this->name === '' ) return '';

		$name = explode( ' ', $this->name );

		return $name[0];
	}

Leave a comment