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

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


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");});


The mysql query

SHOW INDEXES FROM persons

will give you back all of the indexes on the table, however it includes additional info other than just the names. In my setup, the column containing the name is called Key_name so lets get a collection of key names

collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')

And since its a collection you can use contains so finally we have:

if (collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique')) {        $table->dropUnique('persons_body_unique');}


In the simple form, you can do this

Schema::table('persons', function (Blueprint $table) {    $index_exists = collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique');    if ($index_exists) {        $table->dropUnique("persons_body_unique");    }})