|
| 1 | +<?php |
| 2 | + |
| 3 | +/* app/Console/Commands/DeleteUnusedPuppyImages.php */ |
| 4 | + |
| 5 | +namespace App\Console\Commands; |
| 6 | + |
| 7 | +use App\Models\Puppy; |
| 8 | +use Illuminate\Console\Command; |
| 9 | +use Illuminate\Support\Facades\Storage; |
| 10 | + |
| 11 | +class DeleteUnusedPuppyImages extends Command |
| 12 | +{ |
| 13 | + /** |
| 14 | + * The name and signature of the console command. |
| 15 | + * |
| 16 | + * @var string |
| 17 | + */ |
| 18 | + protected $signature = 'delete-unused-puppy-images'; |
| 19 | + |
| 20 | + /** |
| 21 | + * The console command description. |
| 22 | + * |
| 23 | + * @var string |
| 24 | + */ |
| 25 | + protected $description = 'Clean up uploaded images that are no longer referenced in the database.'; |
| 26 | + |
| 27 | + /** |
| 28 | + * Execute the console command. |
| 29 | + */ |
| 30 | + public function handle() |
| 31 | + { |
| 32 | + |
| 33 | + // ------------------------------ |
| 34 | + // Find unused images |
| 35 | + // ------------------------------ |
| 36 | + |
| 37 | + // Get all stored images in `puppies` directory |
| 38 | + $storedImages = Storage::disk('public')->files('puppies'); |
| 39 | + // Get all images referenced by puppies |
| 40 | + $usedImages = Puppy::pluck('image_url') |
| 41 | + // adjust the path to match stored images |
| 42 | + ->map(fn($url) => str_replace('/storage/', '', $url)) |
| 43 | + ->toArray(); |
| 44 | + |
| 45 | + // Compare both arrays |
| 46 | + $unusedImages = array_diff($storedImages, $usedImages); |
| 47 | + |
| 48 | + |
| 49 | + // ------------------------------ |
| 50 | + // Report |
| 51 | + // ------------------------------ |
| 52 | + |
| 53 | + $totalCount = count($unusedImages); |
| 54 | + |
| 55 | + if ($totalCount === 0) { |
| 56 | + $this->info('No unused images found!'); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + $this->info('Found ' . $totalCount . ' unused images.'); |
| 61 | + // Show name for first 3 images, and then "+ X more..." if any. |
| 62 | + $firstThree = array_slice($unusedImages, 0, 3); |
| 63 | + foreach ($firstThree as $image) { |
| 64 | + $this->line('- ' . $image); |
| 65 | + } |
| 66 | + if ($totalCount > 3) { |
| 67 | + $remaining = $totalCount - 3; |
| 68 | + $this->line("+ {$remaining} more..."); |
| 69 | + } |
| 70 | + |
| 71 | + // ------------------------------ |
| 72 | + // Delete (upon confirmation) |
| 73 | + // ------------------------------ |
| 74 | + |
| 75 | + if ($this->confirm('Do you want to delete these unused images?')) { |
| 76 | + foreach ($unusedImages as $image) { |
| 77 | + Storage::disk('public')->delete($image); |
| 78 | + $this->info('Deleted: ' . $image); |
| 79 | + } |
| 80 | + $this->info('Unused images deleted successfully.'); |
| 81 | + } else { |
| 82 | + $this->info('Operation cancelled.'); |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments