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

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);

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);

Tags:

Laravel