How to add and drop indexes in Laravel schema builder - BOOKC -->

How to add and drop indexes in Laravel schema builder

Tuesday, April 4, 2017


On your laravel database migration you can define indexes for each table that you create, for example you can add primary key, unique value, or just a basic index. All can be done in laravel schema builder.

How to add indexes
The schema builder supports several types of indexes. There are two ways to add them. First, you may fluently define them on a column definition, or you may add them separately:

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

Below is a list of all available index types in laravel:
CommandDescription
$table->primary('id');Adding a primary key
$table->primary(array('first', 'last'));Adding composite keys
$table->unique('email');Adding a unique index
$table->index('state');Adding a basic index


How to delete/drop indexes
It is also possible to drop index using schema builder in laravel To drop an index you must specify the index's name. Laravel assigns a reasonable name to the indexes by default. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:



CommandDescription
$table->dropPrimary('users_id_primary');Dropping a primary key from the "users" table
$table->dropUnique('users_email_unique');Dropping a unique index from the "users" table
$table->dropIndex('geo_state_index');Dropping a basic index from the "geo" table