I would like to cleanup the locally seeded storage images when running php artisan migrate:fresh --seed
.
I noticed that all the database tables get dropped before the seeders even start. So my method for cleaning up local storage images was never touched:
private function cleanLocalFileSystem()
{
$files = File::all();
$files->each(function (File $file) {
$this->fileController->destroy($file->id); // removes associated files from storage.
});
}
So there must be a way to clear out theses images at the start of running the migrate:fresh --seed
command.
Right?
I suggest you create a custom artisan command on your project since Laravel may not have a direct command to handle it. So the idea is so allow you clean up before you migrate.
https://laravel.com/docs/11.x/artisan#registering-commands
php artisan make:command CleanupThenMigrate
Next, you write your logic for the created command. Go to 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);
}
}
}
**
Next, run php artisan app:cleanup-then-migrate
I hope this helps.