55 lines
1.4 KiB
PHP
55 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Product;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\File;
|
|
|
|
class DeleteUnusedUploads extends Command {
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'uploads:cron';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Deletes unused image uploads';
|
|
|
|
public function __construct() {
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle() {
|
|
// Define the absolute path to the uploads directory
|
|
$uploadDirectory = storage_path('app/public/product-images/');
|
|
|
|
// Get all files in the directory
|
|
$files = File::allFiles($uploadDirectory);
|
|
|
|
// Loop through each file in the directory
|
|
foreach ($files as $file) {
|
|
|
|
// Get the relative path of the filev
|
|
$relativePath = 'product-images/' . str_replace($uploadDirectory, '', $file->getPathname());
|
|
|
|
|
|
// If the file doesn't exist in the database, delete it
|
|
$products = Product::whereJsonContains('images', $relativePath)->get();
|
|
|
|
if (count($products) < 1) {
|
|
echo time() . ' Deleting ' . $relativePath . PHP_EOL;
|
|
File::delete($file); // Delete the file from server
|
|
}
|
|
}
|
|
}
|
|
}
|