Laravel. How to Clean Temporary Files

Temporary files tend to grow with times and can quickly become the reason your disk space has shrinked. Below you can find a snippet which will help you to clean the your app temporary folder from outdated files. There is a time frame set to define for how long to keep the files. This is curretly set to delete files older than 1 day, which you free change as best fits your app.

$fileList = \Storage::disk('media')->allFiles('temp');
$deletedFileCount = 0;
foreach ($fileList as $filePath) {
    $lastModified = \Storage::disk('media')->lastModified($filePath);
    $keepTime = time() - 1 * 24 * 60 * 60; // 1 day
    if ($lastModified < $keepTime) {
$this->comment('  - Deleted ' . $deletedFileCount . ' files');

Add this as a job to the scheduler to run every day and off you go.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form. Links to this article are welcome

Other Related Articles