目的
ダミーデータを作る際に、「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