Created
December 7, 2021 12:40
-
-
Save j-dexx/c9f3e320e1ce82d7c2759b9cd808c7dc to your computer and use it in GitHub Desktop.
Update already ran laravel migrations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Console\Commands; | |
| use Illuminate\Console\Command; | |
| use Illuminate\Support\Facades\DB; | |
| class UpdateAlreadyRunMigrations extends Command | |
| { | |
| /** | |
| * The name and signature of the console command. | |
| * | |
| * @var string | |
| */ | |
| protected $signature = 'migrate:update-already-run'; | |
| /** | |
| * The console command description. | |
| * | |
| * @var string | |
| */ | |
| protected $description = 'Sets already run migrations in the migrations table'; | |
| /** | |
| * Create a new command instance. | |
| * | |
| * @return void | |
| */ | |
| public function __construct() | |
| { | |
| parent::__construct(); | |
| } | |
| /** | |
| * Execute the console command. | |
| * | |
| * @return int | |
| */ | |
| public function handle() | |
| { | |
| $migrationsToAdd = $this->migrationsToAdd(); | |
| $batchNumber = $this->getBatchNumber() + 1; | |
| foreach($migrationsToAdd as $migrationToAdd) { | |
| DB::table('migrations') | |
| ->insert([ | |
| 'migration' => $migrationToAdd, | |
| 'batch' => $batchNumber | |
| ]); | |
| } | |
| } | |
| private function getBatchNumber(): int | |
| { | |
| return DB::table('migrations')->max('batch') ?: 0; | |
| } | |
| private function migrationsToAdd(): array | |
| { | |
| $migrationNames = $this->getMigrationNames(); | |
| $alreadyRunMigrations = $this->getAlreadyRunMigrationNames(); | |
| return array_diff($migrationNames, $alreadyRunMigrations); | |
| } | |
| private function getAlreadyRunMigrationNames(): array | |
| { | |
| return DB::table('migrations') | |
| ->select('migration') | |
| ->pluck('migration') | |
| ->toArray(); | |
| } | |
| private function getMigrationNames(): array | |
| { | |
| $migrationNames = []; | |
| foreach($this->getFilePaths() as $filePath) { | |
| $migrationNames[] = $this->migrationName($filePath); | |
| } | |
| return $migrationNames; | |
| } | |
| private function migrationName(string $path): string | |
| { | |
| return str_replace('.php', '', basename($path)); | |
| } | |
| private function getFilePaths(): array | |
| { | |
| $migrationsPath = base_path('database/migrations/'); | |
| return glob($migrationsPath . "*.php"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment