Laravel Migration Primary Index

Primary Index

The Primary Index constraint uniquely identifies each row in a table. Primary indexes must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary index. Primary Index can be composite (multiple).

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

Create Primary Index

Create a primary index with articles_id_primary name.

// or

Drop Primary Index

articles_id_primary - is name of Primary Index.

  • articles - table name
  • id - index column
  • primary - type of index/key

Create Composite Primary Index

Create a composite primary index with articles_id_parent_id_primary name.

$table->primary(['id', 'parent_id']);

Drop Composite Primary Index

articles_id_parent_id_primary - is name of Composite Primary Index with id and parent_id columns.

  • articles - table name
  • id - first column
  • parent_id - second column
  • primary - type of index/key

Creare Primary Index With Custom Name

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

// primary index
$table->primary('id', 'custom_primary_index_name');

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

Rename Index

$table->renameIndex('articles_id_parent_id_primary', 'articles_id_parent_id_primary_custom')