phplaravellaravel-7laravel-migrationsmysql-error-1068

Laravel 7 migration: Syntax error or access violation: 1068 Multiple primary key defined


When I try to do php artisan migrate it gives me this error Illuminate\Database\QueryException:

SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (SQL: alter table users add primary key users_user_id_primary(user_id))

I'm pretty new to Laravel, tho

Here are my migrations:

User migration

    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id('user_id')->primary();
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('password');
    });
}

Post migration

    public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id('post_id');
        $table->timestamps();
        $table->string('content');
        $table->foreignId('user_id')->constrained();
        $table->primary(['post_id', 'user_id']); 


    });
}

Categories migration

    public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id('id_cat')->primary();
        $table->string('nom');
        
    });
}

Marques migration

    public function up()
{
    Schema::create('marques', function (Blueprint $table) {
        $table->id('marque_id');
        $table->foreignId('cat_id')->constrained();
        $table->string('designation');
        $table->primary(['marque_id','cat_id']); 
    });
}

UserMarques migration

    public function up()
{
    Schema::create('user_marques', function (Blueprint $table) {
        $table->foreignId('cat_id')->constrained();
        $table->foreignId('marque_id')->constrained();
        $table->timestamps();
    $table->primary(['marque_id','user_id']); 
    });
}

Solution

  • Use $table->increments('user_id'); instead of $table->id('user_id')->primary();

    and with others.

    BTW, i prefer only id instead of with model name, so in this case i prefer this: $table->increments('id');

    Update for Laravel 7.x

    Laravel 7.x migration comes with id method

    public function id($column = 'id')
    {
        return $this->bigIncrements($column);
    }
    

    so in this case: you can use id like this

    $table->id();
    

    PS: increments key comes with primary key