Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can indexes be checked if they exist in a Laravel migration?

Tags:

Trying to check if a unique index exists on a table when preparing a migration, how can it be achieved?

Schema::table('persons', function (Blueprint $table) {     if ($table->hasIndex('persons_body_unique')) {         $table->dropUnique('persons_body_unique');     } }) 

Something that looks like the above. (apparently, hasIndex() doesn't exist)

like image 980
Oladipo Avatar asked Aug 25 '17 13:08

Oladipo


People also ask

What is index in Laravel migration?

It's the way to say to the Laravel Migration to add indices to that column, in order to get faster results when searching through that particular column. It's a common procedure in DB design when building tables. Just "index" some particular columns if you plan to make searchs in the table using those columns.

What is index in migration?

Migration is the process by which Content Manager OnDemand moves index data from the database to archive storage. Migration optimizes database storage space while allowing you to maintain index data for a very long time.

How does Laravel keep track of migrations?

Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations. If you would like to specify a custom output path for the generated migration, you may use the --path option when executing the make:migration command.

How do I check if a table is indexed in MySQL?

To see the index for a specific table use SHOW INDEX: SHOW INDEX FROM yourtable; To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA.


1 Answers

Using "doctrine-dbal" that Laravel uses is better solution:

Schema::table('persons', function (Blueprint $table) {     $sm = Schema::getConnection()->getDoctrineSchemaManager();     $indexesFound = $sm->listTableIndexes('persons');      if(array_key_exists("persons_body_unique", $indexesFound))         $table->dropUnique("persons_body_unique"); }); 
like image 101
admirko Avatar answered Sep 19 '22 14:09

admirko