Search code examples
laraveldatabase-migrationlaravel-5.5laravel-5.6

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`))

Solution

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

    change to

    $table->dropUnique('users_email_unique');