Laravel: how to add a foreign key reference for user

If you need to add a foreign key reference to the user in the foreign table, you should know that id column formats must match  in users & new tables.

Example:

Create a user table (by default in Laravel 8):

Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});

In this case, we see that the type of id is not clearly specified, but if you look in the database, you can see that it is bigint(20)

 

Add foreign key reference example:

Schema::create('example_table', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->bigInteger('user_id')->unsigned();
$table->timestamps();

$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});

 

 

Comments

No comments yet, you can leave yours: