Skip to content

Instantly share code, notes, and snippets.

@muhiminulhasan
Created November 21, 2024 16:26
Show Gist options
  • Select an option

  • Save muhiminulhasan/6ee5adf79c4257b908e7909d60cdcfdb to your computer and use it in GitHub Desktop.

Select an option

Save muhiminulhasan/6ee5adf79c4257b908e7909d60cdcfdb to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class SafeMigrate extends Command
{
protected $signature = 'migrate:safe';
protected $description = 'Run migrations safely, skipping already migrated files';
public function handle()
{
$this->info('Starting safe migration...');
// Get all migration files
$migrationFiles = glob(database_path('migrations/*.php'));
$migrations = [];
foreach ($migrationFiles as $file) {
$migrations[] = basename($file, '.php');
}
// Get already migrated files
if (Schema::hasTable('migrations')) {
$migratedFiles = DB::table('migrations')->pluck('migration')->toArray();
} else {
$migratedFiles = [];
}
// Find new migrations
$newMigrations = array_diff($migrations, $migratedFiles);
if (empty($newMigrations)) {
$this->info('No new migrations to run.');
return;
}
// Run each new migration
foreach ($newMigrations as $migration) {
try {
$this->info("Migrating: {$migration}");
// Include and run the migration file
require_once database_path("migrations/{$migration}.php");
$className = $this->getClassNameFromFile($migration);
if ($className) {
$instance = new $className();
$instance->up();
// Record the migration
DB::table('migrations')->insert([
'migration' => $migration,
'batch' => DB::table('migrations')->max('batch') + 1
]);
$this->info("Migrated: {$migration}");
}
} catch (\Exception $e) {
$this->error("Error migrating {$migration}: " . $e->getMessage());
continue;
}
}
$this->info('Migration completed successfully.');
}
private function getClassNameFromFile($migration)
{
$content = file_get_contents(database_path("migrations/{$migration}.php"));
if (preg_match('/class\s+(\w+)\s+extends/i', $content, $matches)) {
return $matches[1];
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment