mdeveloper
mdeveloper

Reputation: 123

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();
        });

Upvotes: 8

Views: 15744

Answers (3)

Manuel Guzman
Manuel Guzman

Reputation: 533

In case somebody gets to this question, now laravel allows to use the foreignUuid method:

$table->foreignUuid('userId')
    ->constrained()
    ->cascadeOnDelete();

Upvotes: 4

Naufal Shoeria
Naufal Shoeria

Reputation: 41

change your code from

$table->unsignedBigInteger('userId');

to

$table->foreign('userId')

if use laravel 8 you can typing like that

$table->foreignUuid('user_id');

Upvotes: 4

OMR
OMR

Reputation: 12218

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);

Upvotes: 10

Related Questions