LoginSignup
3
1

More than 3 years have passed since last update.

LaravelでS3にある画像を全てローカルにコピーする

Last updated at Posted at 2018-04-07

Artisanコマンドを作成し、「php artisan dev:images」などを実行してコピー出来るようにします。その際のhandle関数はこちら。

App\Console\Commands\CopyS3FilesToStorage.php
/**
 * 保存するS3バケットのディレクトリ
 *
 * @var array
 */
protected $shouldCopyDirectories = [
    'user-profile-images',
    'team-profile-images',
];

public function handle()
{
    $prodS3Disk = Storage::disk('s3');

    // ディレクトリにある全てのファイルを一次元配列として取得
    // ディレクトリの中にディレクトリがあっても再帰的に取得されます
    $allFiles = array_reduce($this->shouldCopyDirectories, function ($stack, $directory) use ($prodS3Disk) {
        array_push($stack, ...$prodS3Disk->allFiles($directory));
        return $stack;
    }, []);

    // ファイル数を取得しプログレスを開始
    $bar = $this->output->createProgressBar(count($allFiles));

    $publicDisk = Storage::disk('public');

    // コピー処理
    foreach ($allFiles as $file) {
        // 既にコピーされていればコピーを実行しません
        if (!$publicDisk->exists($file)) {
            $publicDisk->put($file, $prodS3Disk->get($file));
        }

        // プログレスを進める
        $bar->advance();
    }

    // プログレスを終了
    $bar->finish();
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1