I'm trying to create a foreign key using Laravel's migration.
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsinged();
$table->string('title');
$table->longText('body');
$table->timestamp('published_at');
$table->timestamps();
});
Schema::table('articles', function($table) {
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
I'm getting the following error, when I do php artisan migrate
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter ta blelaravel_articles
add constraint articles_user_id_foreign foreign key (user_id
) referenceslaravel_users
(id
) on delete cascade) `
You have a typo in the method name. It's supposed to be unsigned()
not unsinged()
:
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->longText('body');
$table->timestamp('published_at');
$table->timestamps();
});
The Schema Builder uses Fluent
to chain the methods, which doesn't throw an exception even if the chained method unsinged
doesn't exist. The articles
table would still be created despite the typo, but the user_id
column would be a signed integer, and since the id
column in the users
table is an unsigned integer it will prevent the constraint from being created.