My Solution
Botble has functionality for handling media files, but no specific command automatically scans and registers existing files in the storage directory. However, you can use the following approach:
First, copy your media files with their folder structure to the destination project’s storage directory (typically storage/app/public/ for publicly accessible files).
You could use the RvMedia::uploadFromPath()
method that is used to upload files with programmatically.
You would need to create a custom command to scan the directories and register the files.
Here’s a simplified example of how you could create such a command:
<?php
namespace App\Console\Commands;
use Botble\Base\Facades\BaseHelper;
use Botble\Media\Facades\RvMedia;
use Botble\Media\Models\MediaFile;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand('cms:media:import', 'Import media files from storage directory')]
class ImportMediaFilesCommand extends Command
{
public function handle(): int
{
BaseHelper::maximumExecutionTimeAndMemoryLimit();
$mediaPath = storage_path('app/public');
$this->components->info('Scanning media directory...');
// Get only original files (skip thumbnails)
$files = collect(File::allFiles($mediaPath))
->filter(function ($file) {
// Skip files that match thumbnail pattern (e.g. filename-150x150.jpg)
return !preg_match('/-\d+x\d+\.\w+$/', $file->getFilename());
});
$this->components->info(sprintf('Found %d files to import', $files->count()));
$count = 0;
$mediaFiles = [];
foreach ($files as $file) {
try {
$relativePath = str_replace($mediaPath . '/', '', $file->getPath());
$folder = $relativePath ?: null;
$mediaFile = RvMedia::uploadFromPath($file->getRealPath(), 0, $folder);
if ($mediaFile) {
$mediaFiles[] = $mediaFile;
$count++;
}
if ($count % 100 === 0) {
$this->components->info(sprintf('Imported %d files', $count));
}
} catch (\Throwable $exception) {
$this->components->warn('Error when importing file: ' . $file->getRealPath());
$this->components->warn($exception->getMessage());
}
}
$this->components->info(sprintf('Successfully imported %d files', $count));
// Generate thumbnails
if ($this->confirm('Do you want to generate thumbnails now?', true)) {
$this->components->info('Generating thumbnails...');
foreach ($mediaFiles as $mediaFile) {
try {
RvMedia::generateThumbnails($mediaFile);
} catch (\Throwable $exception) {
$this->components->warn('Error generating thumbnails for: ' . $mediaFile->url);
}
}
$this->components->info('Thumbnails generated successfully!');
}
return self::SUCCESS;
}
}