With Laravel, create a custom attribute in the User Model to get the users full name and explain it to me. Format output with Markdown including format code with Markdown triple backticks.
Adding a custom extended attribute “full name” to the User model is quite simple.
First, we create a getFullNameAttribute()
method on the User model that'll return the users first name and last name, separated with a space. The attribute name must start with get
and end with Attribute
and the name between them will become the attribute name we can access in our application.
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
Now, we can access that attribute using the $user
model directly.
echo $user->full_name
Alternatively, we could access it via Eloquent's $appends
variable to make sure this attribute is always included in Eloquent models' toArray()
and toJson()
outputs.
protected $appends = ['full_name'];