Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unique constraint from a column using Laravel migrations?

I have to remove a unique constraint from an email column using Laravel migrations. Here is my code:

class AlterEmailToUsers extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('email')->unique(false)->nullable()->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
       $table->string('email')->nullable(false)->unique()->change();
    });
}

}

But when I run php artisan migrate, I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_email_unique' (SQL: alter table `users` add unique `users_email_unique`(`email`))
like image 719
aishazafar Avatar asked Apr 13 '18 07:04

aishazafar


People also ask

How do I drop unique index in laravel migration?

You can drop it just simply using [] around field name: Schema::table('guests', function(Blueprint $table) { $table->dropUnique(['email']); }); UPD: By the latest docs for 9. x it's still relevant.

How do I change a column to unique in laravel migration?

$table->unique('slug'); So you add unique index to existing 'slug'.

How do I drop a unique key constraint in MySQL?

The syntax for dropping a unique constraint in MySQL is: ALTER TABLE table_name DROP INDEX constraint_name; table_name.


2 Answers

The provided solution works just fine but just one small tip here:
You can pass an array with the name of the column like so:

$table->dropUnique(['email']); 

in this case, Laravel will generate the index name automatically based on its conventions

like image 115
4unkur Avatar answered Oct 11 '22 18:10

4unkur


 public function up()
 {
   Schema::table('users', function (Blueprint $table) {
    $table->string('email')->unique(false)->nullable()->change();
   });
  }

change to

$table->dropUnique('users_email_unique');
like image 34
Kuldeep Mishra Avatar answered Oct 11 '22 20:10

Kuldeep Mishra