Laravel migration shows "Multiple primary key defined"

2k Views Asked by At

My Laravel migration is like below

public function up()
{
    Schema::create('account_main', function (Blueprint $table) {
      $table->increments('user_sn')->primary();
      $table->string('member_username', 20);
      $table->string('login_password', 255);
      $table->integer('login_count')->default('0')->unsigned();
    });
}

When I ran php artisan migrate, it shows the following error:

1068 Multiple primary key

Could someone help to find the problem?

2

There are 2 best solutions below

0
BadPiggie On BEST ANSWER

In Laravel Eloquent ORM the type increments will be defined as primary key automatically. So don't need to use primary() method.

If the column is integer.

$table->increments('user_sn');

If the column is string

$table->string('user_sn')->primary();

If you want any other column to be unique (instead of primary key)

$table->increments('user_sn');
$table->string('member_username', 20)->unique(); // cannot contain duplicate values
0
Alberto On

You don't need the ->primary() because already ->increments('...') includes it.
It's like if in MySQL you write this:

PK INT AUTO_INCREMENT PRIMARY KEY;
PRIMARY KEY(PK)

You are declaring two times the same primary key