I’m writing an API Resource. I think it’s about OOP. In the first code, the fullName
field is empty, more precisely, only last_name
comes. But in the second code it works exactly as I wanted it. What is the reason of this?
FÄ°RST
public function toArray($request) { return [ 'user_id' => $this->id, 'email' => $this->email, 'description' => $this->description, 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'full_name' => $this->firstname . ' ' . $this->last_name, ]; }
SECOND
public function toArray($request) { $firstName = $this->first_name; $lastName = $this->last_name; $fullName = $firstName . ' ' . $lastName; return [ 'user_id' => $this->id, 'email' => $this->email, 'description' => $this->description, 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'full_name' => $fullName, ]; }
Advertisement
Answer
You have $this->firstname
in the first one. It should be $this->first_name
. So it should look like this:
'full_name' => $this->first_name . ' ' . $this->last_name,