DEV Community

Cover image for Auto-Delete Files After Download In Laravel πŸ˜Ž
Mahmoud Ramadan
Mahmoud Ramadan

Posted on

1

Auto-Delete Files After Download In Laravel πŸ˜Ž

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

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay