Auto-Delete Files After Download In Laravel 😎
Mahmoud Ramadan

Mahmoud Ramadan @mmramadan496

About: Computer Science Geek 🧐 || Software Engineer 👨‍💻 || Digging Code Creator 🚀

Location:
Mansoura, Dakahlia, Egypt
Joined:
Jan 15, 2024

Auto-Delete Files After Download In Laravel 😎

Publish Date: Feb 21 '25
1 0

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();
}
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment