Laravel 11 Xoá các file ảnh ,file tài liệu cũ

Laravel 11 Xoá các file ảnh ,file tài liệu cũ

Tạo service FileService để xử lý các dữ liệu liên quan đến file \app\Services\FileService.php

<?php

namespace App\Services;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class FileService
{
    public $timestamp;
    /**
     * Recursively get all files in a directory.
     *
     * @param string $directory
     * @return array
     */
    public function getAllFiles($directory, $disk = 'public')
    {
        $files = [];
        $directoryContents = Storage::disk($disk)->allFiles($directory);
        foreach ($directoryContents as $file) {
            $files[] = $file;
        }

        $subdirectories = Storage::disk($disk)->allDirectories($directory);
        // Remove duplicate file paths if any
        $files = array_unique($files);
        return $files;
    }
    public function delete_file(string $file, $disk = 'public')
    {
        try {
            Storage::disk($disk)->delete($file);
            Log::info("Deleted: $file");
            return 1;
        } catch (\Exception $e) {
            return 0;
        }
    }
    public function __construct()
    {
        $this->timestamp = Carbon::now()->format('Y_m_d_H_i_s');
    }

    /**
     * Tạo tên file export
     * @param string $fileName
     * @param string $type
     * @return string
     */
    public function setname_file(string $fileName, string $type = 'xlsx'): string
    {
        return $fileName . '_' . $this->timestamp . '.' . $type;
    }
}

Tạo command để xoá file DeleteFileOldCommand.php

<?php

namespace App\Console\Commands\Export;

use App\Services\FileService;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Throwable;

class DeleteFileOldCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
//    protected $signature = 'app:delete-file-old-command {--days_ago=30}';
    protected $signature = 'app:delete-file-old-command {days_ago}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command xóa các file cũ ';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // dùng nếu php artisan app:delete-file-old-command --days_ago=10
        // $days_ago =(int) $this->option('days_ago');
        //dùng nếu php artisan app:delete-file-old-command 10
        $days_ago = (int)$this->argument('days_ago');
        $fileserivce = new FileService();
        $files = $fileserivce->getAllFiles('');
        // Define the time limit (e.g., 24 hours)
        $timeLimit = Carbon::now()->subSeconds($days_ago);
        foreach ($files as $file) {
            $lastModified = Carbon::createFromTimestamp(Storage::disk('public')->lastModified($file));
            if ($lastModified->lessThan($timeLimit)) {
                $fileserivce->delete_file($file);
            }
        }
        $this->info('Old files deleted successfully.');
    }

    public function fail(Throwable|string|null $exception = null)
    {
        $this->info('Failed to delete');
    }
}

Xong ta tạo crontab để chạy auto \routes\console.php

<?php

.....
use Illuminate\Support\Facades\Schedule;

......
Schedule::command('app:delete-file-old-command 10')->at('3:00')->runInBackground()->onOneServer()->timezone('Asia/Ho_Chi_Minh');
......

Vậy là xong