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
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));
}
}