Search code examples
laravel-5.1dingo-api

Laravel 5 dingo api, add multiple transformed objects to the response


Want to add a transformed object along with other response, I have used following code:

$accessToken = Authorizer::issueAccessToken();

    $user = User::where('email', $request->get('username'))->with('profile')->first();
    if ($user) {
        $accessToken['user'] = $this->response->item($user, new UserTransformer);
    }

    return $accessToken;

Expected Response:

{
    "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer",
    "expires_in": 31536000,
    "data": {
      "id": 1,
      "email": "xxxxx",
      "profile": {
        "data": {
          "id": 1,
          "first_name": "Muhammad",
          "last_name": "Shakeel",
        }
      }
    }
}

but not getting transformed object, there must be some better way to add multiple transformed objects with response. Am I missing something?

Edit Current response returns user object without transformation and if I return only user transformed object like following, it returns correct transformed object:

return $this->response->item($user, new UserTransformer);

Solution

  • As discussed on the issue tracker(https://github.com/dingo/api/issues/743#issuecomment-160514245), jason lewis responded to the ticket with following:

    The only way you could do this at the moment would be to reverse that. So you'd return the response item, then add in the access token data, probably as meta data.

    So, something like this.

    return $this->response->item($user, new UserTransformer)->setMeta($accessToken);
    

    The response will then contain a meta data key which will contain your access token data.