Skip to content

Instantly share code, notes, and snippets.

@skalero01
Last active May 9, 2019 05:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skalero01/fffb760e818c5a6b1adb899dfd534c58 to your computer and use it in GitHub Desktop.
Save skalero01/fffb760e818c5a6b1adb899dfd534c58 to your computer and use it in GitHub Desktop.
Laravel command for moving media libraries from "media" (local) to S3
<?php
/*
* Instructions
* Remove all the media string on here for the folder set on the public folder on the filesystem
* On this example the S3 disk is the set on the filesystem options and the media disk is set on the media librarys configuration file
*/
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Spatie\MediaLibrary\Models\Media;
use Illuminate\Support\Facades\Storage;
class MoveImagesToS3 extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'images:move';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Move local images to S3';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$medias = Media::where('disk', 'media')->get();
foreach ($medias as $media) {
$this->moveToS3($media->getUrl());
$conversions = $media->getMediaConversionNames();
foreach ($conversions as $conversion) {
$this->moveToS3($media->getUrl($conversion));
}
$this->deleteDirectories($media);
$media->update(['disk' => 's3']);
}
}
public function deleteDirectories($media)
{
$directory = $media->getUrl();
$directory = str_replace('/media', '', $directory);
$directory = $this->removeLastOnUrl($directory);
$this->deleteDirectory($directory);
}
public function deleteDirectory($directory)
{
$files = Storage::disk('media')->allFiles($directory);
if(count($files)==0) {
Storage::disk('media')->deleteDirectory($directory);
}
}
public function moveToS3($url)
{
$url = urldecode($url);
// Move media
$url = str_replace('/media', '', $url);
$media = Storage::disk('media')->get($url);
Storage::put($url, $media, 'public');
// Delete FIle
Storage::disk('media')->delete($url);
}
private function removeLastOnUrl($directory)
{
$directory = explode('/', $directory);
unset($directory[count($directory)-1]);
$directory = implode('/', $directory);
return $directory;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment