Forked from Razoxane/laravel_conditional_index_migration.php
Created
October 13, 2022 12:34
-
-
Save websterl3o/3c1ccbbb35306caa782ecd1f34a6c113 to your computer and use it in GitHub Desktop.
Laravel - Create Index If Not Exists / Drop Index If Exists
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 | |
use Illuminate\Support\Facades\Schema; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Database\Migrations\Migration; | |
class LaravelConditionalIndexMigration extends Migration | |
{ | |
/** | |
* Run the migrations. | |
* | |
* @return void | |
*/ | |
public function up() | |
{ | |
Schema::table('tablename', function (Blueprint $table) { | |
$sm = Schema::getConnection()->getDoctrineSchemaManager(); | |
$doctrineTable = $sm->listTableDetails('tablename'); | |
if (! $doctrineTable->hasIndex('singlecolumnindexname')) { | |
$table->index('column1', 'singlecolumnindexname'); | |
} | |
if (! $doctrineTable->hasIndex('multicolumnindexname')) { | |
$table->index(['column2', 'column3'], 'multicolumnindexname'); | |
} | |
}); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down() | |
{ | |
Schema::table('tablename', function (Blueprint $table) { | |
$sm = Schema::getConnection()->getDoctrineSchemaManager(); | |
$doctrineTable = $sm->listTableDetails('tablename'); | |
if ($doctrineTable->hasIndex('singlecolumnindexname')) { | |
$table->dropIndex('singlecolumnindexname'); | |
} | |
if ($doctrineTable->hasIndex('multicolumnindexname')) { | |
$table->dropIndex('multicolumnindexname'); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment