Check if a unique unique key exists in Laravel

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

Is there any method or way to check if an index key exists (e.g. a unique key)?

+8
php mysql laravel
source share
2 answers

While Laravel provides no way to check for a key, you can use any available queries in MySQL and then use DB::select() .

For example:

 $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 with the correct values.

+13
source share

If you use Laravel, then most likely you will have access to ORM, for example, to Eloquent. Assuming you are using Eloquent, you can 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) { } 
+5
source share

All Articles