0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelで「画像フォルダを一括削除する自作コマンド」を作成する手順

Posted at

目的

ダミーデータを作る際に、「php artisan migrate:fresh --seed」を複数回やるとこれまで「php artisan migrate:fresh --seed」で生成してきた画像データが残ったまま新しい画像データを生成してしまう。
毎回「画像データを削除 → ダミー画像生成」の流れを作りたい

手順

ステップ1:Artisanコマンドを作成

php artisan make:command ClearCollectionImages

成功すると:

Console command created successfully.

以下のファイルが作成される👇
app/Console/Commands/ClearCollectionImages.php

ステップ2:コマンドの中身を書く

ClearCollectionImages.php を以下のように編集👇

ClearCollectionImages.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class ClearCollectionImages extends Command
{
    // コマンド名(ここが実行時に使うやつ)
    protected $signature = 'storage:clear-collection-images';

    // 説明(`php artisan list` に出るやつ)
    protected $description = 'storage/app/public/collection_images の画像をすべて削除します';

    public function handle()
    {
        $directory = 'collection_images';

        if (!Storage::disk('public')->exists($directory)) {
            $this->warn("📂 ディレクトリが存在しません: storage/app/public/{$directory}");
            return Command::SUCCESS;
        }

        $files = Storage::disk('public')->files($directory);

        if (empty($files)) {
            $this->info("🧼 削除する画像はありませんでした。");
            return Command::SUCCESS;
        }

        foreach ($files as $file) {
            Storage::disk('public')->delete($file);
        }

        $this->info("🗑️ {$directory} 内の画像を削除しました。削除数: " . count($files));

        return Command::SUCCESS;
    }
}

ステップ3:コマンドを登録する

app/Console/Kernel.php を開いて、commands に登録👇

app/Console/Kernel.php
// app/Console/Kernel.php

protected $commands = [
    \App\Console\Commands\ClearCollectionImages::class,
];

ステップ4:実行

php artisan storage:clear-collection-images
php artisan migrate:fresh --seed
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?