If you are going to create a search system or assume the body column will be searched, then it is good practice to make it indexed. In this tutorial, I will show you how to add mysql index in laravel migration. From this laravel migration indexing tutorial, you will learn laravel migration add unique index.

I will show how to create or add single column index or laravel migration index multiple columns. So let us start laravel migration create index. So we will do the following things for laravel migration create unique index.

Single column index example 

See the example code of how to add mysql index in laravel migration:

<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('body')->index();
            $table->boolean('status')->default(false);
        });
    }

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

 

Multiple column index example 

See the example of laravel migration index multiple columns:

<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('body');
            $table->boolean('status')->default(false);
            $table->index(['name', 'body']);
        });
    }

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

 

Now if you run php artisan migrate then you will see the following output:

how-to-add-index-column-laravel-migration

Read also: How To Add Enum Column In Laravel Migration?

 

Conclusion

I have tried to discuss the clear concept of how to add mysql index in laravel migration. Now we know laravel migration add index on column. Hope this laravel migration index multiple columns tutorial will help you.