Laravel Migrations: Indexes

Creating Indexes

$table->string('email')->unique();
$table->unique('email');
$table->index(['account_id', 'created_at']);
$table->unique('email', 'unique_email');

Renaming Indexes

$table->renameIndex('from', 'to')

Dropping Indexes

Schema::table('geo', function (Blueprint $table) {
    $table->dropIndex(['state']); // Drops index 'geo_state_index'
});

To drop an index, you must specify the index's name.

By default, Laravel automatically assigns a reasonable name to the indexes.

  • $table->dropPrimary('users_id_primary');.
  • $table->dropUnique('users_email_unique');.
  • $table->dropIndex('geo_state_index');.
  • $table->dropSpatialIndex('geo_location_spatialindex');.

Foreign Key Constraints

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});
$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');
$table->dropForeign('posts_user_id_foreign');
$table->dropForeign(['user_id']);
Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

Foreign key constraints use the same naming convention as indexes.

Laravel Migrations: Indexes — Structure map

Clickable & Draggable!

Laravel Migrations: Indexes — Related pages: