share-lt/app/Console/Commands/ImportImages.php

62 lines
1.8 KiB
PHP
Raw Normal View History

<?php
namespace App\Console\Commands;
use App\Models\Entry;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class ImportImages extends Command
{
protected $signature = 'app:import-images {--entry-id=1}';
protected $description = 'Import images into the media library';
public function handle(): void
{
$entryId = $this->option('entry-id');
$entry = Entry::find($entryId);
if (!$entry) {
$this->error("Entry with ID {$entryId} not found");
return;
}
$files = Storage::disk('public')->files('imported_images');
if (empty($files)) {
$this->info('No files found in storage/app/public/imported_images/');
return;
}
$this->info("Found " . count($files) . " files to import");
foreach ($files as $filePath) {
try {
$fullPath = storage_path('app/public/' . $filePath);
$fileName = pathinfo($fullPath, PATHINFO_BASENAME);
if (!file_exists($fullPath)) {
$this->error("File not found: {$fullPath}");
continue;
}
// Check if already exists
$existingMedia = $entry->getMedia()->where('file_name', $fileName)->first();
if ($existingMedia) {
$this->info("Skipping existing: {$fileName}");
continue;
}
$media = $entry->addMedia($fullPath)
->toMediaCollection('default');
$this->info("Imported: {$fileName}");
} catch (\Exception $e) {
$this->error("Failed to import {$filePath}: " . $e->getMessage());
}
}
$this->info('Import completed');
}
}