mshakeel
mshakeel

Reputation: 612

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);

Upvotes: 1

Views: 1134

Answers (2)

mshakeel
mshakeel

Reputation: 612

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.

Upvotes: 1

Bharat Geleda
Bharat Geleda

Reputation: 2780

I got it to work using Internal Requests. https://github.com/dingo/api/wiki/Internal-Requests

So what you can do is

Suppose you have a route that fetches transformed user object at api/users/{email_id}?access_token=...

While issuing the access_token you can do the following :

$dispatcher = app('Dingo\Api\Dispatcher');
$array = Authorizer::issueAccessToken();

$array['user'] = $dispatcher->get('api/users/'.$request->get("username").'?access_token='.$array['access_token']);
return $array;

This will return transformed data.

NOTE : You will need to have a route that fetches user data.

You will have to handle cases in /api/users/{email-id} where email-id does not exist.

Upvotes: 0

Related Questions