猿问

为什么 Laravel API 资源数据是这样的?

我正在编写 API 资源。我认为这是关于OOP的。在第一个代码中,该fullName字段是空的,更准确地说,只是last_name来了。但在第二个代码中,它完全按照我想要的方式工作。这是什么原因呢?


第一的


 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,

        ];

    }

第二


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,

    ];

}


弑天下
浏览 74回答 1
1回答

慕哥9229398

你有$this->firstname第一个。应该是的$this->first_name。所以它应该看起来像这样:'full_name' => $this->first_name . ' ' . $this->last_name,
随时随地看视频慕课网APP
我要回答