Laravel 5.6 - Pass additional parameters to API Resource?

前端 未结 6 977
天涯浪人
天涯浪人 2020-12-28 17:26

A Laravel API Resource can be either a single resource or a collection. In some cases, additional parameters are required to be passed to the resource/collection from the co

6条回答
  •  自闭症患者
    2020-12-28 18:21

    This simple trick worked for me in Laravel 5.8 :)

    Controller

    $user = User::find($user->id);
    $user->access_token = $tokenResult->accessToken; // Add additional data
    return new ProfileResource($user);
    

    Resource

    public function toArray($request)
    {
        return [
            'id'            => $this->id,
            'picture'       => $this->picture,
            'first_name'    => $this->first_name,
            'last_name'     => $this->last_name,
            'active'        => $this->active,
            'access_token'  => isset($this->access_token) ? $this->access_token : '', // Additional data
        ];
    }
    

提交回复
热议问题