27

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`))
Jan Żankowski
  • 8,690
  • 7
  • 38
  • 52
aishazafar
  • 1,024
  • 3
  • 15
  • 35

3 Answers3

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

change to

$table->dropUnique('users_email_unique');
Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26
23

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

4unkur
  • 827
  • 9
  • 14
2

I went through this problem, when using softDeletes on all tables, which caused this need, for new users, once deleted logically.

So, I created a migration by setting the users table (--table=users) and placed the removal of the constraint, but then I redid the action for possible new inclusion needs.

But I used it only because of the softDeletes, be careful with your business rules. I keep validating existence in request rules.

The code is as follows (up and down methods only):

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


public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->unique(['email']);
    });
}
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Jeremy Caney Jul 11 '22 at 01:26