Files
sam-api/app/Console/Commands/CleanupTempFiles.php
2026-03-11 17:49:16 +09:00

60 lines
1.4 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Commons\File;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class CleanupTempFiles extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'storage:cleanup-temp';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Delete temporary files older than 7 days';
/**
* Execute the console command.
*/
public function handle(): int
{
$threshold = now()->subDays(7);
$files = File::where('is_temp', true)
->where('created_at', '<', $threshold)
->get();
$count = $files->count();
$this->info("Found {$count} temp files to delete");
$deleted = 0;
foreach ($files as $file) {
try {
// Delete physical file
if (Storage::disk('r2')->exists($file->file_path)) {
Storage::disk('r2')->delete($file->file_path);
}
// Force delete from DB
$file->forceDelete();
$deleted++;
} catch (\Exception $e) {
$this->error("Failed to delete file ID {$file->id}: {$e->getMessage()}");
}
}
$this->info("Cleanup completed: {$deleted}/{$count} files deleted");
return Command::SUCCESS;
}
}