Home > Net >  (Laravel/PHP) How to save file in memory or delete file before return without causing error?
(Laravel/PHP) How to save file in memory or delete file before return without causing error?

Time:10-05

(It's API only) I'm using JasperPHP to generate reports, the user can choose the extension (xls or pdf). After I process the data, then I save the file/report locally, it's in "storage/app/jasper/example1234.pdf".

So at the end of the function I do this:

    // more code
    $file = $path . $filename . '.' . $extension; // file path
    // more code
    return response()->file($file);

And it works, I can get the file using ReactJS. OK! But I wanted to delete the file before the "return", but if I do that the file will not be read on the "return". That's why I wanted to save it in a variable/memory first, delete the file locally and then return.

Note I tried to get the file using several methods, such as "Storage::get()", but they all generate errors on "return", stating that "string file" is expected but "resource" was given.

CodePudding user response:

Response facade has deleteFileAfterSend() method. You can use it like the following:


return response()->file($file)->deleteFileAfterSend();

  • Related