Download json without creating a file or delete file after return

Viewed 113

i am trying to let an user download a collection as a json file, but i don't know how to do it, without storing the file.

option 1: download without storing at all

i tried something like this

return response()->download(WorkPersonalReport::all(), 'zapis_prac.json');

this does not work, because it is not a file. can i make it a "pseudo file"?

option 2: create file, let the download happen, delete file

public function jsonExport() {
  $wprs = WorkPersonalReport::all();
  file_put_contents('assets/workPersonalReport.json', $wprs);

  return response()->download('assets/workPersonalReport.json', 'zapis_prac.json');
}

with

public function index() {
  unlink('assets/workPersonalReport.json');
}

is either of the options possible with optimal code?

first - just to create a temporary file, which will be deleted after the download goes through?

second - unlink() the file after return statement, instead of everytime index() is called?

1 Answers

Consider the following snippet;

return response(WorkPersonalReport::all(), 200, [
    'Content-Disposition' => 'attachment; filename="collection.json"'
]);
Related