laravel - 如何删除超过一小时的公共(public)存储文件?

标签 laravel cron laravel-7

我正在开发一个项目,需要从 storage/public/dir_name/ 中删除所有文件。示例文件名为jIK4uh.png。我应该使用 cron 作业来完成这项任务。这是我正在遵循的方法。

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

然后运行php artisan Schedule:run

现在如何按照此策略选择所有早于过去一小时的文件并每小时删除这些文件?或者有其他有效的想法来做这件事吗?

Laravel 版本:7.30

最佳答案

基本思想是使用存储lastModified日期时间

从文件中获取最后修改的日期时间

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

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

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

   //delete file here
}

如果您将文件名存储在数据库中,则可以根据文件上传日期删除

已更新

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

关于laravel - 如何删除超过一小时的公共(public)存储文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68001014/

相关文章:

laravel - Laravel 中的软删除不会隐藏 View 中的记录

php - 仅运行脚本一次,持续 5 分钟 (Linux)

php - 如何在 php-fpm-alpine docker 容器内运行 cron 作业?

laravel - 在 laravel 7x 的路径中找不到文件

mysql - Eloquent 中一个查询的多个求和

php - laravel ORM 关系 : left Join like query with optional condition on the right table

PHP Laravel - HTML 表单值数组

php - 每二十四小时自动更新一次mysql表

Laravel Errorbag​​ 无法在 Blade 组件内工作

php - laravel elasticsearch babenkoivan/elastic-adapter模型关系