
Hello mates
Inside this article, I will be sharing, how to add an index to column in laravel migration. As well as I will be sharing, how to create migration in laravel with an example.
For this article, i am assuming, you already have installed Laravel and configured database details. But if not please do.
Let’s begin with creating migrations.
Open terminal or cmd or integrated terminal if you are using vs code. and write bellow command to create a migration.
php artisan make:migration create_posts_table
Done. Just created laravel migration. and let add some columns with index.
Add index to column
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('post_title');
$table->string('post_slug');
$table->text('post_content');
$table->timestamps();
$table->index(['post_title', 'post_slug', 'created_at']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
Next, run the migration command
php artisan migrate
Done! now please check your database, you will see the post has been created and columns are indexed
But you know, slug should be unique. So we should add a unique index to the post_slug column instead of just the index. Let’s do that
How to add a unique index in laravel migration
Modify first `function up` like bellow
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('post_title');
$table->string('post_slug');
$table->text('post_content');
$table->timestamps();
$table->unique(['post_slug']);
$table->index(['post_title', 'created_at']);
});
}
That’s it. But you should know that adding unique to post_slug is not enough, you have to handle that programmatically, otherwise, you may see the mysql error.
How to add index to an existing column
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class AddIndexToLeads extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('gallery', function(Blueprint $table)
{
$table->index('post_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('gallery', function (Blueprint $table)
{
$table->dropIndex(['post_id]);
//see this, used an arrya notation here, becuase index name is
//different than column name, if used array notation, Laravel will auto guess
// the index name.
});
}
}
How to Rename Indexes
$table->renameIndex('from', 'to')
Hope this helped you!


Leave a Reply