How to make column unique and index it in Laravel Migration?
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
When working on a database or migrating your tables, it is essential to ensure the data integrity by making certain columns unique and indexing them for faster retrieval. This article aims to explain how to do this efficiently in Laravel migrations.
Understanding Migrations
Laravel's migration system allows you to manage your database structure by creating and running migrations with a single command. These migrations are stored within the `database/migrations` directory, each containing an up() and down() method for making changes and reverting them, respectively.Making Columns Unique
To make columns unique in your Laravel migration table, you need to ensure the data within those columns always has a distinct value. Here's how to achieve that: 1. Define a primary key column for your table if it doesn't already have one. This will prevent duplicate entries from being created and help maintain uniqueness across your rows. 2. If you are using a text or string data type, define a unique constraint on the specific column with something like this:php
public function up()
{
Schema::table('inventories', function($table)
{
$table->string('sku',255)->unique();
});
}php
public function up()
{
Schema::table('inventories', function($table)
{
$table->bigIncrements('id'); // ensures unique id values
});
}Making Columns Unique and Indexed Efficiently
Indexing your columns not only ensures uniqueness but also improves the performance of your queries by making it easier for your database to find specific data efficiently. Here's how you can add an index to your unique column: 1. Define a primary key if not already in place, and ensure that the column is defined as "unique" as discussed earlier. 2. Create a migration file named `2022_01_15_add_unique_index_to_inventories_table` within `database/migrations`. 3. In this new migration file, define an up() method to add the index and the down() method to remove it in case of migration failure or rollback:php
public function up()
{
Schema::table('inventories', function($table)
{
$table->unique('sku'); // define unique constraint on sku column
$table->index('sku_index'); // add index to the sku column
});
}
public function down()
{
Schema::table('inventories', function($table)
{
$table->dropUnique('sku'); // remove unique constraint on sku column
$table->dropIndex('sku_index'); // remove index from the sku column
});
}