djave_co's avatar

Laravel 5.2 Response::stream alternative

I'm getting a bit muddled with a CSV download. I'm very happy to save it to a file and supply a link to the user, but this seems like the wrong way to go judging from things like these.

Going from this answer http://stackoverflow.com/questions/26146719/use-laravel-to-download-table-as-csv#answer-27596496 I think I've found that the stream() method no longer exists.

public function download()
{
    $headers = [
            'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'
        ,   'Content-type'        => 'text/csv'
        ,   'Content-Disposition' => 'attachment; filename=galleries.csv'
        ,   'Expires'             => '0'
        ,   'Pragma'              => 'public'
    ];

    $list = $this->users->getAllUsers()->toArray();

    # add headers for each column in the CSV download
    array_unshift($list, array_keys($list[0]));

   $callback = function() use ($list) 
    {
        $FH = fopen('php://output', 'w');
        foreach ($list as $row) { 
            fputcsv($FH, $row);
        }
        fclose($FH);
    };

    // return Response::stream($callback, 200, $headers); // Old version
    return response()->download($callback, 'Users-' . date('d-m-Y'), $headers);
    
}

I've tried to use the Laravel 5.2 response() function, however I'm just getting a bit lost as to what I'm responding with – `download seems the logical option, but that gives me the following error:

Object of class Closure could not be converted to string

Which makes sense. What is the right way of going about this? Or should I save the file and then just use the filepath as the first argument of my download() function – something that seems to be bad practise?

0 likes
2 replies
justrusty's avatar
Level 1

Use the response helper function

return response()->stream($callback, 200, $headers);

faisalsharif's avatar

Call to undefined method Laravel\Lumen\Http\ResponseFactory::stream()

lumen 5.6

Please or to participate in this conversation.