Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete Unique key on multiple columns?

How do I reverse a unique key added on multiple columns in Laravel? Basically, what should go in the down() function of this migration code:

public function up()
{
    Schema::table('topics', function($table)
    {
        $table->unique(array('subject_id', 'grade_id', 'semester_id', 'name'));
    }
}


/**
 * Reverse the migrations.
 *
 * @return void
 */

public function down()
{
    Schema::table('topics', function($table)
    {

    }
}
like image 435
Favourite Onwuemene Avatar asked Dec 08 '22 07:12

Favourite Onwuemene


2 Answers

To drop a unique index, you use dropUnique('name_of_index').

If you're not specifying an index name in the second parameter of unique(), the name of the index will be tableName_fieldsSeperatedByUnderscore_unique.

public function down()
{
    Schema::table('topics', function($table)
    {
        $table->dropUnique('topics_subject_id_grade_id_semester_id_name_unique');
    }
}
like image 175
Marwelln Avatar answered Dec 11 '22 08:12

Marwelln


There are two approaches to drop unique index :

First Approach : In dropUnique() function we can pass array so that you don't need to use exact unique index name like "tableName_fieldsSeperatedByUnderscore_unique". Here is code snippet

Schema::table('users', function (Blueprint $table) {
      $table->dropUnique(['email']);
});

This will drop the unique index of column 'email'.

Second Approach: This approach is exactly same as described by Marwelln,still I would like to put it here again. You can pass unique index name in the dropUnique(), it will also work. But be sure that you are confident about unique index name.Code for that looks like this:

Schema::table('users', function (Blueprint $table) {
          $table->dropUnique('users_email_unique');
});
like image 45
VIjay J Avatar answered Dec 11 '22 07:12

VIjay J