Orange Lux
Orange Lux

Reputation: 1977

Laravel : Force the download of a string without having to create a file

I'm generating a CSV, and I want Laravel to force its download, but the documentation only mentions I can download files that already exist on the server, and I want to do it without saving the data as a file.

I managed to make this (which works), but I wanted to know if there was another, neater way.

    $headers = [
        'Content-type'        => 'text/csv',
        'Content-Disposition' => 'attachment; filename="download.csv"',
    ];
    return \Response::make($content, 200, $headers);

I also tried with a SplTempFileObject(), but I got the following error : The file "php://temp" does not exist

    $tmpFile = new \SplTempFileObject();
    $tmpFile->fwrite($content);

    return response()->download($tmpFile);

Upvotes: 57

Views: 37931

Answers (3)

omarjebari
omarjebari

Reputation: 5519

A Laravel 7 approach would be (from the docs):

$contents = 'Get the contents from somewhere';
$filename = 'test.txt';
return response()->streamDownload(function () use ($contents) {
    echo $contents;
}, $filename);

NOTE: Headers can be added to streamDownload() as a third parameter as an associative array.

Upvotes: 37

Brian Dillingham
Brian Dillingham

Reputation: 9356

Make a response macro for a cleaner content-disposition / laravel approach

Add the following to your App\Providers\AppServiceProvider boot method

\Response::macro('attachment', function ($content) {

    $headers = [
        'Content-type'        => 'text/csv',
        'Content-Disposition' => 'attachment; filename="download.csv"',
    ];

    return \Response::make($content, 200, $headers);

});

then in your controller or routes you can return the following

return response()->attachment($content);

Upvotes: 72

Paulo Costa
Paulo Costa

Reputation: 38

Try this:

// Directory file csv, You can use "public_path()" if the file is in the public folder
$file= public_path(). "/download.csv";
$headers = ['Content-Type: text/csv'];

 //L4
return Response::download($file, 'filename.csv', $headers);
//L5 or Higher
return response()->download($file, 'filename.csv', $headers);

Upvotes: -6

Related Questions