Home > Software engineering >  Generating and downloading a text file on the fly in Laravel
Generating and downloading a text file on the fly in Laravel

Time:12-26

My data is stored in the database and I need to give it out of it in a text file. There is no point in creating a file on disk, but an attempt to generate a response with a file does not work. Found a way like this but it doesn't work ERR_INVALID_RESPONSE

 $contents = 'My data from db';
     
   $filename = 'example.txt';

   return response()->streamDownload(function () use ($contents) {
         echo $contents;
     }, $filename);

CodePudding user response:

In your route name the route with something reasonable like:

Route::get('filename.txt', [FooController::class, 'foo']);

And in your controller at foo() action:

$headers = [
    'Content-Type' => 'application/plain',
    'Content-Description' => 'File name',
];

$contents = 'My data from db';

return \Response::make($contents, 200, $headers);
  • Related