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?
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.
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With