skip to Main Content

Hi friends This is my code in laravel:

Schema::create('programmer', function (Blueprint $table) {
            $table->id();
            $table->string('email', 155)->unique();
            $table->integer('primary')->primary();
            $table->timestamps();
});

I got this error:

SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (Connection: mysql, SQL: alter table programmer add primary key (primary))

2

Answers


  1. A table can have only ONE primary key, as id() also is a primary key so you got "Multiple primary key defined" error,

    You can mix multiple column as a single primary key like this:

    Schema::create('programmer', function (Blueprint $table) {
                $table->id();
                $table->string('email', 155)->unique();
                $table->integer('primary');
                $table->primary(['id', 'primary']); // Adds composite keys.
                $table->timestamps();
    });
    
    Login or Signup to reply.
  2. The error you are getting is because you are trying to define two primary keys for the programmer table. The id() method automatically creates an auto-incrementing primary key, so you don’t need to define another primary key.

    To fix the error, you can remove the primary() method from the primary column definition. Your migration code should look like this:

    Schema::create('programmer', function (Blueprint $table) {
            $table->id();
            $table->string('email', 155)->unique();
            $table->integer('primary');
            $table->timestamps();
    });
    

    If you must want to create ‘primary’ column as primary key, Your migration code should look like this:

    Schema::create('programmer', function (Blueprint $table) {
            $table->id();
            $table->string('email', 155)->unique();
            $table->integer('primary');
            $table->primary('primary');
            // If you want to add multiple primary key use array as like below
            // $table->primary(['primary', 'email']);
            $table->timestamps();
    });
    

    The primary() method now only takes the name of the primary column as its argument. This tells Laravel that the primary column is the primary key for the programmer table.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search