How to delete public storage files older than last one hour?

Viewed 738

I'm working on a project which requires deleting all files from storage/public/dir_name/. Example file name is jIK4uh.png. I am supposed to use a cron job for this task. Here is the method I'm following.

app/console/commands/ClearPublicStorage.png

class ClearPublicStorageCron extends Command {

  protected $signature = 'storage:clear';
  
  public function handle()
  {
      Log::info("Public storage files cleared!");

      // tasks logic here

      $this->info('Cron command run successfully');
  }
}

app/Console/Kernel.php

class Kernel extends ConsoleKernel {
  protected function schedule(Schedule $schedule)
    {
        $schedule->command('storage:clear')->hourly();
    }
}

Then running php artisan schedule:run

Now how to select all files that are older than last one hour and delete those in every hour by following this strategy? Or any other efficient idea to do this stuff ?

Laravel version : 7.30

2 Answers

Basic idea is to using storage lastModified datetime

get last modified datetime from file

$fileTime=Storage::disk('public')->lastModified('dummy.pdf');

$fileModifiedDateTime=Carbon::parse($fileTime);

if(Carbon::now()->gt($fileModifiedDateTime->addHour())){

   //delete file here
}

If you are storing filename in database then you can delete based on file uploaded date

Updated

$files = Storage::disk("public")->allFiles("claim-images");
    
foreach ($files as $file) {
   $time = Storage::disk('public')->lastModified($file);
   $fileModifiedDateTime = Carbon::parse($time);
    
   if (Carbon::now()->gt($fileModifiedDateTime->addHour(1))) {
                
        Storage::disk("public")->delete($file);
    }
    
     //storage symbolic link files not required to delete.Still providing here for you reference
    
   if (File::exists(public_path('storage/' . $file))) {
        
         File::delete(public_path('storage/' . $file));
   }
}

This might help you.

First I am getting all files from temp-files folder and put them in collection.

Looping through the collection and comparing each file last modified date and time to now()->addHour() and if it is older file will be deleted.

public function deleteOldFiles() {
    $files = collect(Storage::allFiles('temp-files'));
    $files->each(function ($file) {
         $lastModified =  Storage::lastModified($file);
         $lastModified = Carbon::parse($lastModified);

         if (Carbon::now()->gt($lastModified->addHour())) {
             Storage::delete($file);
         }
     });

    return true;
}
Related