Search code examples
mysqllaravelmigrationuuid

Adding new UUID foreign key into existing table using laravel migration


I want to add new column in my users table which is uuid so here is the code

Schema::table('users', function (Blueprint $table) {
    $table->uuid('uuid')->nullable()->unique();
});

and then i want to make a relation using foreign key in my skills table, and in this skills table already has foreign key from another table but it always showing error Foreign key constraint is incorrectly formed

Schema::table('skills', function (Blueprint $table) {
   $table->foreignUuid('user_id')->nullable();
   $table->foreign('user_id')
         ->references('uuid')
         ->on('users')
         ->onDelete('cascade');
});

is it posible i cant add new foreign key just because i havent drop and redeclare the existing foreign key ? why i ask that is because when i add uuid foreign key in my trainings table that has no foreign key at all is success here is the code

Schema::table('trainings', function (Blueprint $table) {
   $table->foreignUuid('user_id')->nullable();
   $table->foreign('user_id')->references('uuid')->on('users');
});

here is the error

SQLSTATE[HY000]: General error: 1005 Can't create table db_masteremployee.skills (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table skills add constraint skills_user_id_foreign foreign key (user_id) references users (uuid) on delete cascade)


Solution

  • i think its because the uuid is not a primary key so i decided to use this instead

    Schema::table('users', function (Blueprint $table) {
         $table->dropPrimary('id');
         $table->uuid('uuid')->nullable()->unique();
         $table->primary(['id','uuid']);
    });
    

    and if you dont want to drop the existing primary key, you can just make a simple column and make your self a relation BelongsTo() / HasMany() in the model

        Schema::table('users', function (Blueprint $table) {
            $table->uuid('uuid')->nullable();
        });
    
        Schema::table('skills', function (Blueprint $table) {
            $table->uuid('user_id')->nullable();
        });
    

    the relation code

     public function skills(): Hasmany
    {
        return $this->hasmany(Skills::class, 'user_id', 'uuid');
    }