phpmysqllaraveldatabase-migration

How can indexes be checked if they exist in a Laravel migration?


Trying to check if a unique index exists on a table when preparing a migration, how can it be achieved?

Schema::table('persons', function (Blueprint $table) {
    if ($table->hasIndex('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
    }
})

Something that looks like the above. (apparently, hasIndex() doesn't exist)


Solution

  • Using "doctrine-dbal" that Laravel uses is better solution:

    Schema::table('persons', function (Blueprint $table) {
        $sm = Schema::getConnection()->getDoctrineSchemaManager();
        $indexesFound = $sm->listTableIndexes('persons');
    
        if(array_key_exists("persons_body_unique", $indexesFound))
            $table->dropUnique("persons_body_unique");
    });