1

I want to get Laravel database table's indexes.

I know I can get them as below

\DB::select("SHOW INDEX FROM $db_table_name WHERE non_unique = 1 AND column_name = '$db_column_name'");

But I think it's not good way. I want to get them like:

// this
\DB::getIndex($db_table_name, $db_column_name);

// Or this
\DB::table($db_table_name)->getIndex($db_column_name);

I think I have to extend query builder.
Please tell me how to do.

Edit--
I use
Laravel Framework 5.6.39
PHP 7.2.17

2
  • What version of Laravel are you using? Commented May 10, 2019 at 6:17
  • Sorry, I forget. I use Laravel Framework 5.6.39. Commented May 10, 2019 at 6:18

1 Answer 1

5

Yes, you will need to extend the query builder, so you can place this code in your AppServiceProvider boot method, or if you have a custom service provider:

use Illuminate\Database\Query\Builder; // at the top of the class

Builder::macro('getIndex', function($columnName){
   return $this->getConnection()
           ->select("show index from {$this->from} where non_unique = 1 and column_name='$columnName'");
});

Then to use it:

DB::table('TABLE_NAME')->getIndex('COLUMN_NAME');

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.