Larvel 5.6.3 PHP 7.2.10
I am getting this following error for php artisan migrate:fresh
General error: 1215 Cannot add foreign key constraint (SQL: alter table `videos` add constraint `videos_video_identified_by_foreign` foreign key (`video_identified_by`) references `users` (`id`))
user table migation file -> 2014_10_12_000000_create_users_table
videos table migration file -> 2018_12_02_122553_create_videos_table
Normally it happens when parent table is not existing and we are using its column as foreign key in our table, but as it can be seen users table should be created first and then videos table will be created, then why I am getting this error.
users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
videos
Schema::create('videos', function (Blueprint $table) {
$table->increments('video_id');
$table->text('video_link');
$table->text('video_description');
$table->string('video_category');
$table->string('video_language');
$table->unsignedInteger('video_identified_by');
$table->timestamps();
});
Schema::table('videos', function($table) {
$table->foreign('video_identified_by')->references('id')->on('users');
});
hi try this is work fine for me
<?php
$table->integer('video_identified_by')->unsigned();
$table->foreign('video_identified_by')->references('id')->on('user')
->onUpdate('RESTRICT')->onDelete('CASCADE');
?>
then php artisan migrate:refresh
ah you make change in your id in table video try this
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->text('video_link');
$table->text('video_description');
$table->string('video_category');
$table->string('video_language');
$table->integer('video_identified_by')->unsigned();
$table->foreign('video_identified_by')->references('id')->on('users')
->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('videos');
}
Add onDelete Cascade and change unsignedInteger to unsigned
Schema::create('videos', function (Blueprint $table) {
$table->increments('video_id');
$table->text('video_link');
$table->text('video_description');
$table->string('video_category');
$table->string('video_language');
$table->unsigned('video_identified_by');
$table->timestamps();
});
Schema::table('videos', function($table) {
$table->foreign('video_identified_by')->references('id')->on('users')-
>onDelete('cascade');
});