Check if a unique index key exists in Laravel

If you are using Laravel then most likely you will have access to an ORM like Eloquent. Assuming you are using Eloquent, you might be able to do something like this:

try {
    Schema::table(
        'the_name_of_your_table',
        function (Blueprint $table) {
            $sm = Schema::getConnection()->getDoctrineSchemaManager();
            $indexesFound = $sm->listTableIndexes('the_name_of_your_table');

            $indexesToCheck = [
                'index_name_1',
                'index_name_2',
                'index_name_3',
                'index_name_4'
            ];

            foreach ($indexesToCheck as $currentIndex) {
                if (array_key_exists($currentIndex, $indexesFound)) {
                    // The current index exists in the table, do something here :)
                }
            }
        }
    );
} catch (Exception $e) {

}

While Laravel doesn't provide any method to check the existence of a key, you could use any of the available queries in MySQL and then use DB::select().

For instance:

$keyExists = DB::select(
    DB::raw(
        'SHOW KEYS
        FROM your_table_name
        WHERE Key_name=\'your_key_name\''
    )
);

Just replace your_table_name and your_key_name for the correct values.

Tags:

Mysql

Php

Laravel