Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a unique index key exists in Laravel

Tags:

php

mysql

laravel

The Schema\Builder class has a hasTable() and hasColumn() methods to check the existence of a table and a column, respectively.

Is there any method or way to check if an index key (such as a unique key) exists?

like image 524
Luís Cruz Avatar asked May 28 '15 11:05

Luís Cruz


2 Answers

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.

like image 134
Luís Cruz Avatar answered Nov 06 '22 02:11

Luís Cruz


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) {

}
like image 23
jpruiz114 Avatar answered Nov 06 '22 03:11

jpruiz114