Trying to download the stream gives a file with content of “Resource id #xxx”

I’m using Laravel, and am trying to export items in my database to a CSV file. I am getting pretty close. Unfortunately, I get an output of Process id #xxx in the downloaded file.

This is a more minimal and anonymous example of the code I’ve been using.

public function exportCSV(): StreamedResponse
{
    $keys = ['id', 'title'];
    $posts = Post::select($keys)->get();

    $stream = fopen('php://memory', 'w+');
    fputs($stream, "sep=,n"); // Excel will be nice
    fputcsv($stream, $keys);

    foreach ($posts->toArray() as $post) fputcsv($stream, $post);

    rewind($stream);

    // dd(stream_get_contents($stream)) gives the expected result here
    return response()->streamDownload(function () use ($stream) {
        echo $stream;
    }, 'export.csv');
}