简体   繁体   中英

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`))
 public function up()
 {
   Schema::table('users', function (Blueprint $table) {
    $table->string('email')->unique(false)->nullable()->change();
   });
  }

change to

$table->dropUnique('users_email_unique');

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

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']);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM