Laravel 8: Two simple methods to add index in Laravel migration

By | May 28, 2021

An index is a data structure that helps in improving the speed of operations in a table. A user can create indexes for either one column or multiple columns as per his or her requirement. Please note that, after adding an index, only SELECT statements become faster, and INSERT and UPDATE operations can take more time while adding indexes. Keep it in your mind.

Now lets talk about how can we add index in Laravel migration file. First, we will create migration file. Here is the command to create migration.

Please note that: In this example, I am using Laravel 8.

php artisan make:migration products

Method 1: You can add index column by column like following:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class Products extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('product_name')->index('product_name');
            $table->string('product_sku')->index('product_sku');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Method 2:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class Products extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('product_name');
            $table->string('product_sku');
	    $table->index(['product_name', 'product_sku']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

And now, run the below command that will create products table and add the indexes to the columns.

php artisan migrate