Laravel - Using Stream with the new Http client

Viewed 1905

I'm migrating my old system to the new version of Laravel, and I'm having problems with one of my requests...

Basically on this request I receive any file and simply forward it to the user. Here is the old version using Guzzle:

use Symfony\Component\HttpFoundation\StreamedResponse;

public function getMedia($media)
{
    try {
        $response = $this->client->get('media/' . $media, [
                'stream' => true
            ]
        );

        $contentType = $response->getHeader('Content-Type');

        $body = $response->getBody();

        $stream = new StreamedResponse(function () use ($body) {
            while (!$body->eof()) {
                echo $body->read(1024);
            }
        });

        $stream->headers->set('Content-Type', $contentType);

        return $stream;
    } catch (ClientException $e) {
        return response()->json([
            'errors' => json_decode($e->getResponse()->getBody()->getContents())->errors,
            'message' => 'Unfortunately we could not find the requested file'
        ], 404);
    }
}

And the new code that I tried to write, without success:

use Symfony\Component\HttpFoundation\StreamedResponse;

public function getMedia($media)
{
    $response = Http::withOptions([
        'stream' => true
    ])->get("media/{$media}");

    $contentType = $response->header('Content-Type');

    $body = $response->body();

    $stream = new StreamedResponse(function () use ($body) {
        while (!$body->eof()) {
            echo $body->read(1024);
        }
    });

    $stream->headers->set('Content-Type', $contentType);

    return $stream;
}

Does anyone have any idea how to solve this? I don't know what to do anymore...

0 Answers
Related