Skip to content

Instantly share code, notes, and snippets.

@neverything
Created October 18, 2024 09:02
Show Gist options
  • Save neverything/a6e1cc30491b188dc2c3d8bf904414a3 to your computer and use it in GitHub Desktop.
Save neverything/a6e1cc30491b188dc2c3d8bf904414a3 to your computer and use it in GitHub Desktop.
Set Image and Video dimension for the Spatie Laravel Media Library as custom properties: https://silvanhagen.com/writing/image-and-video-dimensions-laravel-media-library
<?php
namespace App\Console\Commands;
use App\Actions\Media\UpdateMediaInfoAction;
use Illuminate\Console\Command;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
class UpdateMediaInfoCommand extends Command
{
protected $signature = 'media:update-info';
protected $description = 'Update dimensions and duration for all media items';
protected UpdateMediaInfoAction $updateMediaInfoAction;
public function __construct(UpdateMediaInfoAction $updateMediaInfoAction)
{
parent::__construct();
$this->updateMediaInfoAction = $updateMediaInfoAction;
}
public function handle(): void
{
$totalMediaItems = Media::count();
if ($totalMediaItems === 0) {
$this->info('No media items found.');
return;
}
$this->info("Processing {$totalMediaItems} media items...");
$progressBar = $this->output->createProgressBar($totalMediaItems);
$stats = [
'updated' => 0,
'already_updated' => 0,
'error' => 0,
'skipped' => 0,
];
Media::chunk(100, function ($mediaItems) use ($progressBar, &$stats) {
foreach ($mediaItems as $mediaItem) {
$result = $this->updateMediaInfoAction->execute($mediaItem);
$status = $result['status'] ?? 'error';
if (isset($stats[$status])) {
$stats[$status]++;
} else {
$stats['skipped']++;
}
$progressBar->advance();
}
});
$progressBar->finish();
$this->newLine(2);
$this->info('Media info update completed!');
$this->table(
['Status', 'Count'],
[
['Updated', $stats['updated']],
['Already Updated', $stats['already_updated']],
['Errors', $stats['error']],
['Skipped', $stats['skipped']],
]
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment