AUTO-DELETE FILE AFTER DOWNLOAD

Feb 18, 2025 Copy Link

If you're using Laravel's methods to download a file, it's important to delete it afterward to avoid overloading the server. While you can manually delete the file using the `File` facade, I recently discovered the  `deleteFileAfterSend` method:

 

/**
 * Download the file of the user then delete it.
 */
public function download(User $user)
{
    $filename = "{$user->name}.txt";

    file_put_contents(public_path($filename), json_encode($user));

    return response()->download(public_path($filename))->deleteFileAfterSend();
}

Share via

Filed in:

Tips Responses
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE