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`))
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.
$table->unique('slug'); So you add unique index to existing 'slug'.
The syntax for dropping a unique constraint in MySQL is: ALTER TABLE table_name DROP INDEX constraint_name; table_name.
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
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('email')->unique(false)->nullable()->change();
});
}
change to
$table->dropUnique('users_email_unique');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With