Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

index on multiple columns laravel

How do you make multiple index columns in a table in Laravel?

In this tutorial, I will give you an example of “How do you make multiple index columns in a table in Laravel”, so you can easily apply it to your Laravel 5, Laravel 6, Laravel 7, Laravel 8, Laravel 9, Laravel 10 and Laravel 11 applications.

Need to make multiple index columns in a table in Laravel?

In Laravel, using indexes in SQL queries can significantly improve the performance of your database operations, especially when dealing with large datasets. Here’s how you can utilize indexes effectively within Laravel:

In Laravel, if you want to create a table with multiple index columns, you can achieve this using the schema builder provided by Laravel’s Eloquent ORM. Here’s how you can create a table with multiple index columns:

php artisan make:migration create_users_table
  • Replace 'table_name' with your actual table name.
  • Replace 'column1' and 'column2' with the names of the columns you want to index.
  • You can add more columns to the table schema as needed.
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email')->unique();
            $table->string('phone_number')->unique();
            $table->string('password');
            $table->text('passport_number')->unique()->index();
            $table->enum('user_type',[1,2]);
            $table->rememberToken();
            $table->timestamps();

            $table->index(['email','passport_number','user_type']);

        });
    }

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

After defining the migration, save the file and run the migration using Artisan CLI:

php artisan migrate

Following these steps, you can create a table with multiple index columns in Laravel using migrations. This efficient approach aligns with Laravel’s ORM conventions, making database management easier within your application.

I hope this article helped you learn  How to index multiple columns in migration in the Laravel application. You may also want to check out our guide on Add custom font in dompdf in Laravel.