skip to Main Content

I am using a third party table which very annoyingly has name and surname fields. The first name goes into name and of course the surname goes into surname.

I want to concat these together in the model as I will need to use the full name many times so I added:

public function getFullNameAttribute() : Attribute
{
    return new Attribute(
        $this->name . ' ' . $this->surname
    );
}

and then added

 protected $appends = ['full_name'];

I thought this would always show my concat field but when I dd the table it is not there.

2

Answers


  1. To define an accessor for an Attribute in Laravel, you need to do it this way and remove the type-hint Attribute from the declaration or replace it with string.

    public function getFullNameAttribute()
    {
       return $this->name . ' ' . $this->surname;
    }
    
    Login or Signup to reply.
  2. You can create accessor method in your model.

    public function getFullName()
    {
        return $this->name.' '.$this->surname;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search