You can get an array of indexes for a table directly using the Schema manager:
$indexes = DB::connection()->getDoctrineSchemaManager()->listTableIndexes($table);
OR
$indexes = Schema::getConnection()->getDoctrineSchemaManager()->listTableIndexes($table);
And then you can get an array of the columns associated with that index key:
$columns = $indexes[ 'primary' ]->getColumns();
This function can be used to find the primary key(s) or unique key(s) for a table you know nothing about:
public function getTablePrimaryOrUniqueKey($table, $key='') {
//get the array of table indexes
$indexes = DB::connection()->getDoctrineSchemaManager()->listTableIndexes($table);
//abort if there are no indexes
if(!is_array($indexes)) return false;
//set up the default array of index keys
$keys = ['primary', 'unique'];
//if a key was passed and it is valid, use it...but cast as an array
if($key!='' && in_array($key, $keys)) $keys = (array) $key;
//loop through the keys array
foreach ( $keys as $key ) {
//keep it honest
if ( array_key_exists( $key, $indexes ) ) {
//get the columns for this key
$columns = $indexes[ $key ]->getColumns();
//if we have an array of columns, we have what we need
if ( is_array( $columns ) ) {
return $columns;
}
}
}
//if you got here, you did not get find what you were looking for
return false;
}