Home > OS >  Laravel request body is not empty if I log it, but becomes empty if I return the response
Laravel request body is not empty if I log it, but becomes empty if I return the response

Time:01-17

I am using YOTI for identity verification. They use a custom RequestBuilder to generate the request, but I think my issue has nothing to do with them. Its actually really simple.

If I \Log::info() the response, then I see the correct data, but right after that I return the data and it becomes empty. Why? I know it is already there. I am calling ->getBody() once and saving the result in a var, so it also cannot be somehow consumed.

Here is the relevant part of the code:

$img = ["img" => $data['base64img']];

$request = (new RequestBuilder())
    ->withBaseUrl('https://api.yoti.com/ai/v1')
    ->withPemFilePath(Storage::disk('other')->path("yoti-age-estimation-access-security.pem"))
    ->withEndpoint('/age-antispoofing')
    ->withPayload(Payload::fromJsonData($img)) // For version < 3, use ->withPayload(new Payload($img))
    ->withMethod('POST')
    ->withHeader('X-Yoti-Auth-Id', env('YOTI_CLIENT_SDK_ID'))
    ->build();

// Execute request
$response = $request->execute();

if ($response->getStatusCode() === 200) {
    $body = $response->getBody();
    \Log::info($body); // Has data
    return ['error' => false, 'result' => $body]; // Has no data, is empty {}
} else {
    return ['error' => true, 'status_code' => $response->getStatusCode()];
}

This is my problem:

$body = $response->getBody();
\Log::info($body); // Has data
return ['error' => false, 'result' => $body]; // Has no data, is empty {}

CodePudding user response:

Replace this

$body = $response->getBody();

to this

$body = $response->getBody()->getContents();

As I remember with getBody() you can only read once.

  • Related