Search code examples
laraveluuid

laravel 7 using as uuid foreign key


I have two tables, in both, I am using UUID to generate an id. after that, I am trying to use one id as a foreign in the second table. as shown the migration does accept what I am doing but when I insert data I get this error

Illuminate/Database/QueryException with message 'SQLSTATE[01000]: Warning: 1265 Data truncated for column 'userId' at row 1 

her is my first tables:

       Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('userName')->unique();
            $table->string('email')->unique();
            $table->boolean('isVerified')->default(false);
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

the second table with the foreign key

Schema::create('tableTwo', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->unsignedBigInteger('userId');
            $table->foreign('userId')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
            $table->timestamps();
        });

Solution

  • your are mapping an integer column to uuid column, different types do the sql constraint can't be done ...

    you should change:

      $table->unsignedBigInteger('userId');
    

    to

     $table->uuid('userId')->nullable(false);