Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ace's avatar
Level 7

Migrations: How can one Add an index to an existing column?

I could not find a modify/change column command for this case in L 4

0 likes
11 replies
Ace's avatar
Level 7

@mstnorris I thought my title was clear and understandable, any pointers appreciated. @mass6 thanks , this means i need to rollback and change the migration file, quite messy :(

mstnorris's avatar

@Ace what is it that you want to change?

Just add a new migration and make your changes in that file within the up() method, and reverse the changes in the down() method.

Ace's avatar
Level 7

@mstnorris this way I will loose the data.

''' [Illuminate\Database\QueryException]
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'trader_
id' (SQL: alter table leads add trader_id varchar(255) not null) '''

@mass6 is master for L5 ?

bobbybouwmann's avatar
Level 88

You can just do this right?

<?php

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

class AddIndexToLeads extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('leads', function(Blueprint $table)
        {
            $table->index('trader_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('leads', function (Blueprint $table)
        {
            $table->dropIndex(['trader_id']);
        });
    }

}

11 likes
JarekTkaczyk's avatar

@Ace You don't need any raw statements for index.

Like @bobbybouwmann above, just pass the name of that index in dropIndex: eg. users_email_index OR an array of column(s) to let laravel guess the name: ['email']

master docs are L5.1, in L4 there is no modify methods.

1 like
JarekTkaczyk's avatar

@bobbybouwmann If you pass a string, then it must be valid index name (not column) eg. users_email_index, but if you wish laravel take care of the name, then pass an array with column(s) name ['email'] (laravel will convert it to the valid index name, ie. users_email_index)

3 likes
Ace's avatar
Level 7

thanks for the explanations!

Please or to participate in this conversation.