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

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

Leave a Comment