我想在运行时清理本地种子存储图像
php artisan migrate:fresh --seed
。
我注意到所有数据库表在播种器启动之前就被删除了。所以我清理本地存储镜像的方法就一直没动过:
private function cleanLocalFileSystem()
{
$files = File::all();
$files->each(function (File $file) {
$this->fileController->destroy($file->id); // removes associated files from storage.
});
}
因此必须有一种方法可以在运行
migrate:fresh --seed
命令开始时清除这些图像。
对吧?
我建议你在你的项目上创建一个自定义的 artisan 命令,因为 Laravel 可能没有直接的命令来处理它。所以我们的想法是让您在迁移之前进行清理。
https://laravel.com/docs/11.x/artisan#registering-commands
php artisan make:command CleanupThenMigrate
接下来,为创建的命令编写逻辑。转到 app/Console/Commands/CleanupThenMigrate.php
**
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class CleanupThenMigrate extends Command
{
protected $signature = 'app:cleanup-then-migrate';
protected $description = '';
/**
* Execute the console command.
*/
public function handle()
{
//
$this->info('Cleaning up local storage images...');
$this->cleanLocalFileSystem();
// Run migrations and seeders
$this->info('Running migrate:fresh...');
$this->call('migrate:fresh');
$this->info('Seeding the database...');
$this->call('db:seed');
$this->info('Hala Madrid! All local images have been deleted. Migration and Seeding is complete too!');
}
private function cleanLocalFileSystem()
{
// Define your local storage path
$storagePath = storage_path('app/public');
// Delete all files in the storage path
$getFiles = File::allFiles($storagePath);
foreach ($getFiles as $file) {
File::delete($file);
}
}
}
**
接下来,运行
php artisan app:cleanup-then-migrate
我希望这有帮助。