Laravel Migration Unique Indexes

Laravel Migrations Laravel Migration Unique Indexes

Unique Indexes

A unique index ensures the index key columns do not contain any duplicate values. Unique Index can be composite (multiple).

Laravel will automatically construct an unique index name based on the table, column names, and index type (unique) when creating an index. To drop an unique index, you must first give it a name.

Create Unique Index

Create a unique index with users_email_unique name.

$table->string('email')->unique();
// or
$table->string('email');
$table->unique('email');

Drop Unique Index

users_email_unique - is name of Unique Index.

  • users - table name
  • email - index column
  • unique - type of index/key
$table->dropUnique('users_email_unique');

Create Composite Unique Index

Create a composite unique index with users_name_email_unique name.

$table->unique(['email', 'name']);

Drop Composite Unique Index

users_name_email_unique - is name of Composite Unique Index.

  • users - table name
  • email - first column
  • name - second column
  • unique - type of index/key
$table->dropUnique('users_name_email_unique');

Creare Unique Index With Custom Name

MySQL has a limit here: 64 characters for unique index name length. You may need to set the index name yourself.

// unique index
$table->unique('id', 'custom_unique_index_name');

// composite unique index
$table->unique(['id', 'parent_id'], 'custom_unique_index_name');

Rename Index

$table->renameIndex('users_name_email_unique', 'users_name_email_unique_custom')