How to set auto increment into non primary key?

Luiz picture Luiz · Mar 21, 2017 · Viewed 10.6k times · Source

How would I set a database auto increment field that is not a primary key on the creation method?

The only way is using a raw query?

DB::statement('ALTER TABLE table CHANGE field field INT(10)AUTO_INCREMENT');

Answer

Niklas S. picture Niklas S. · Mar 21, 2017

It is not implemented to do so. However, I found this over at the Laravel Forums:

Schema::table('table', function(Blueprint $t) {
    // Add the Auto-Increment column
    $t->increments("some_column");

    // Remove the primary key
    $t->dropPrimary("table_some_column_primary");

    // Set the actual primary key
    $t->primary(array("id"));
});

This is not tested but should work. I am not sure about how Laravel calls their primary keys, maybe you have to check that first and adapt the dropPrimary() line in order to make it work.