So I'm trying to set a foreign key in my migrate file for laravel so the user table is simple but I'm trying to use bigIncrements instead of stand increments as such.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id')->unsigned();
$table->string('user_id')->unique();
$table->string('avatar');
$table->string('name');
$table->string('email')->unique();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestampsTz();
});
}
And when I do the other table I try to add foreign key to it I get a error saying the the foreign key is incorrectly formed. I'm confused as to how because I'm matching the column types. Here is the other table.
public function up()
{
Schema::create('social_logins', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->unsigned()->index();
$table->string('provider', 32);
$table->string('provider_id');
$table->string('token')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
Make sure that when you are adding new column in your table, that column should be nullable, and should not be unique. Otherwise you will face error. Because when a new column is created it will be empty(not unique). In that condition you have to rollback the migration.
bigIncrements() The bigIncrements method creates an auto-incrementing UNSIGNED BIGINT (primary key) equivalent column: $table->bigIncrements('id');
How to change data type of column in laravel 9 migration ? Step 1 : Install doctrine/dbal package. Step 2 : Generate migration file. Step 3 : Open generated migration file and update.
Remove unsigned()
from:
$table->bigIncrements('id')->unsigned();
And the other migration should look like this:
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
....
$table->index('user_id');
Reason is primary and foreign references must be of same type.
bigIncrements()
wants unsignedBigInteger()
and increments()
wants unsignedInteger()
If you are using
$table->bigIncrements('id');
as a primary key in a users table:
then use
$table->unsignedBigInteger('user_id'); as foreign key
And if you are using $table->increments('id');
as a primary key in a users table then use
$table->unsignedInteger('user_id'); as freign key.
$table->increments(); creates just integer and $table->bigIncrements(); creates big integer.
so the reference type must be the same.
Read more https://laravel.com/docs/4.2/schema#adding-columns
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With