Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

laravel

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);
like image 266
Marc Brillault Avatar asked Jan 02 '17 11:01

Marc Brillault


2 Answers

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);
like image 167
im_brian_d Avatar answered Nov 09 '22 13:11

im_brian_d


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);
like image 31
omarjebari Avatar answered Nov 09 '22 15:11

omarjebari