Access Violation error in Laravel-4 migration - php

I have migrations as follows:
create_users_table.php
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('username', 64)->unique();
$table->string('email', 255)->unique();
$table->string('password',64);
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
create_predictions_table.php
class CreatePredictionsTable extends Migration {
public function up()
{
Schema::create('predictions', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('fixture_id')->unsigned();
$table->foreign('fixture_id')->references('id')->on('fixtures');
$table->integer('home_team_score_prediction');
$table->integer('away_team_score_prediction');
$table->timestamps();
});
}
public function down()
{
Schema::drop('predictions');
}
}
create_fixtures_table.php
class CreateFixturesTable extends Migration {
public function up()
{
Schema::create('fixtures', function(Blueprint $table) {
$table->increments('id');
$table->integer('home_team_id');
$table->integer('away_team_id');
$table->dateTime('date');
$table->string('venue');
$table->timestamps();
});
}
public function down()
{
Schema::drop('fixtures');
}
}
Initially when I ran the migration using
php artisan migrate
I hadn't added foreign key's. I ran
php artisan migrate:refresh
after adding the foreign key constraints which gave me following errror:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'predictions' already exists (SQL: create table `predictions` (`id` int unsigned not null auto_increment primary key, `user_id` int unsigned not null, `fixture_id` int
unsigned not null, `home_team_score_prediction` int not null, `away_team_score_prediction` int not null, `created_ at` timestamp default 0 not null, `updated_at` timestamp default 0 not null) default character set utf8 collate utf8_unicode_ci)
I think that is because the table was already there (although refresh is supposed to rollback the migrations and run them again)
When I tried to rollback using
php artisan migrate:rollback
I got the following:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constrain t fails (SQL: drop table `users`)
Where am I going wrong? I'm new to migrations, so these might be errors beginners usually get. But I don't understand what exactly I'm doing wrong. I hope someone can help me out here.

migration will continue until it meets some problem. So probably a foreign key has already been added, but its associated table is not created yet due to error. If you are trying to rollback, migration will assume that the table associated with a foreign key exists and it will try to rollback that table too.
However, that table does not exist!
Well, the simplest way is to empty the database and rerun migration. I met this problem before and find it hard to rollback step by step once such a problem occurs.

What I Did
There is a migrations table for Laravel.
Truncate or empty the table, then delete all tables related to your migrations.
If possible remove any constraints to the foreign keys first before deleting the table.
You should be good to go migrating again.
Addition
Take care of the order of deletion of tables in down() function.
Deleting some tables with referential constraints as declared by onDelete() definitely needs constraints to be removed first.
I think that's causing your rollback error.
Look more into your migrations , buddy :-)

Related

PHP Laravel PDOException General error referencing column and referenced column in a foreign key constraint are incompatible

I am currently doing migrations in Laravel via the Terminal, and have these two errors when attempting to use php artisan migrate; I will print errors below:
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 3780 Referencing column 'room_id' and referenced column 'id' in foreign key constraint 'contacts_room_id_foreign' are incompatible.")
/Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
Based on the code contained within the Exception Trace, the issue seems to be within the code below:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id');
$table->unsignedInteger('user2_id');
$table->integer('room_id')->unique();
$table->timestamps();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('contacts');
}
}
any ideas on how I can resolve?
If you're on Laravel 5.8 new migration changed to big increments, so for fixining refrencing error just change integer to bigInteger, for example:
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Will changed to:
$table->bigInteger('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Either change original migration
from
bigIncrements()
to just
increments();
Or In your foreign key column do
bigInteger()
instead of
integer()
The foreign key must be the same as the referencing id,
and hence change
$table->integer('room_id')->unique();
to
$table->unsignedBigInteger('room_id')->unique();
and it does the trick.
PS: you'll get another error
SQLSTATE[42S01]: Base table or view
already exists: 1050 Table...
just delete the table and run php artisan migrate
In Laravel 6.0, migrations are as same as #Payam Khaninejad mentioned. i.e.
$table->bigInteger('user_id')->unsigned()->index();
I am updating that for Laravel 6.0 because, I was following an old tutorial that has shown the same error.
users table
$table->increments('id');
contacts table
$table->integer('user_id')->unsigned(); //adding unsigned() here, will fix the error
$table->foreign('user_id')->references('id')->on('users');
In this case, room_id should be unsigned. Try this:
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id');
$table->unsignedInteger('user2_id');
$table->integer('room_id')->unique()->unsigned();
$table->timestamps();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
}
Also in laravel 7.x you may have to change:
$table->increments('id'); // UNSIGNED INTEGER
// to
$table->id(); // UNSIGNED BIGINT
It seems that it is an issue with tables that were migrated in older versions. Ive got the same problem and in my case I used two differents types of declaration for each foreign keys. "integer" and "unsignedInteger"
$table->integer('webcam_id');
$table->unsignedInteger('user_id');
$table->foreign('webcam_id')
->references('id')
->on('webcam');
$table->foreign('user_id')
->references('id')
->on('users');
I recently ran into this problem during a migration to create a table with a foreign key constraint. I found that it had to due with the collation used on the table. Our DB schema is loaded with a schema file, and that has the table collation set to utf8mb4_0900_ai_ci. It looks like Laravel uses utf8mb4_unicode_ci by default.
I resolved the problem by setting the collation for the table during creation with $table->collation = 'YOUR_COLLATION_VALUE'
For Laravel 8.x, change $table->integer('user_id')->unsigned()->index(); to:
$table->unsignedBigInteger('user_id'); because this is compatible with the id() data type.
in your room migration, change the id as such
$table->id();
it will automatically create bigInteger with name 'id'
then in your contact migration, use
$table->bigInteger('room_id')->references('id')->on('rooms');
same goes to the other foreign keys, just follow above code.
well at least this syntax works on laravel 8
This is due to the foreign keys being set before the rooms table being created. you can fix this by doing the following.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContactsTable extends Migration
{
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id');
$table->unsignedInteger('user2_id');
$table->integer('room_id')->unique();
$table->timestamps();
$table->integer('room_id')->unsigned();
$table->integer('user1_id')->unsigned();
$table->integer('user2_id')->unsigned();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
Schema::enableForeignKeyConstraints();
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('contacts');
Schema::enableForeignKeyConstraints();
}
}

String as Primary Key in Laravel migration

I've had to change a table in my database so that the primary key isn't the standard increments.
Here's the migration,
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->text('code', 30)->primary();
$table->timestamps();
$table->text('name');
$table->text('comment');
});
}
However, MySQL keeps returning with,
Syntax error or access violation: 1170 BLOB/TEXT column 'code' used in
key specification without a key length (SQL: alter table settings
add primary key settings_code_primary(code)
I've tried leaving the normal increments id in there and modifying the table in a different migration but the same thing happens.
Any ideas of what I'm doing wrong?
Laveral Version 5.4.23
Change it to string.
$table->string('code', 30)->primary();

SQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Table

Here my migration table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned();
$table->string('name');
$table->string('email',50)->unique();
$table->string('username');
$table->string('password');
$table->boolean('active');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
when ever i try to migrate the following error occur
*[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists (SQL: create table users (id int unsigned not null auto_incr
ement primary key, role_id int unsigned not null, name varchar(191) not
null, email varchar(50) not null, username varchar(191) not null, pas
sword varchar(191) not null, active tinyint(1) not null, remember_token
varchar(100) null, created_at timestamp null, updated_at timestamp nu
ll) default character set utf8mb4 collate utf8mb4_unicode_ci)
[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists*
please tell me what should i do ?? i have already use migrate:reset or dumpautoload or rollback nothing happen . lots of time i edit or delete this usersfile and recreated it .
Try like this
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration
{
public function up()
{
Schema::dropIfExists('users');
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned();
$table->string('name');
$table->string('email',50)->unique();
$table->string('username');
$table->string('password');
$table->boolean('active');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
this problem is showing when you want migrate tables that exist in database :
for this problem just go to PHPMYADMIN manually and drop all table and now
run command php artisan migrate
DANGER - by dropping a table, rolling back or refreshing your database will destroy all data in that table or database and these methods are not recommended for production use and you should definitely not include drop table behavior in your migration.
It's clear there are a lot of "solutions" for this problem, but all the solutions I read through are very destructive solutions and none of them work for a production database. Yes, they get rid of the error, but at what expense?
Based on the number of solutions, it also seems that there could be several causes to this error.
My error was caused by a missing entry in my migrations table. Which required a very simple solution -- adding the entry back in. A simple issue like this definitely doesn't warrant a database refresh

laravel errno 150 foreign key constraint is incorrectly formed

Can anybody help me to solve this problem?
There are 3 tables with 2 foreign keys:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('firms', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('firm_id')->unsigned()->nullable();
$table->foreign('firm_id')->references('id')->on('firms');
$table->timestamps();
});
Error after running migration:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter ta
ble `firms` add constraint `firms_user_id_foreign` foreign key (`user_id`)
references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed")
In case of foreign keys, the referenced and referencing fields must have exactly the same data type.
You create the id fields in both users and firms as signed integers. However, you create both foreign keys as unsigned integers, therefore the creation of the keys fail.
You need to either add the unsigned clause to the id field definitions, or remove the unsigned clause from the foreign key fields.
This answer is not better than the six answers before it but it is a more comprehensive answer on what causes laravel-errno-150-foreign-key-constraint-is-incorrectly-formed and how to fix specifically for laravel.
1) Spelling : often at times a wrong spelling of the referenced column name or referenced table name can throw up this error and you won't know as the error trace is not very descriptive.
2) Unique : the referenced column must be unique or indexed either by adding ->primary() or adding ->unique() or adding ->index() to the column definition in your migration.
3) Data type : the referenced and referencing fields must have exactly the same data type. this can not be stressed enough.
for bigincrements expected data type is bigInteger('column_name')->unsigned();
for increments expected is integer('column_name')->unsigned(); etc.
4) Remnants : when this error occurs it does not mean that the table is not migrated rather it is migrated but the foreign key columns are not set and it is not added to the migration table hence running php artisan migrate:reset will remove other tables except the faulty tables, so a manual drop of the faulty table is recommended to avoid further errors.
5) Order : this is often the most usual cause of this error the table being referenced must be created or migrated before the reference table else artisan wont find where to integrate the foreign key. to ensure an order for the migration process rename the migration file example:
Table A:2014_10_12_000000_create_users_table.php and
Table B:2014_10_12_100000_create_password_resets_table.php
This indicates that Table A will always come before Table B to change that, i will rename Table B to 2014_10_11_100000_create_password_resets_table.php now it will migrate before Table A.
6) Enable Foreign Key : if all else fails then add Schema::enableForeignKeyConstraints(); inside your function up() before your migration code example:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
To read more see laravel foreign key and laravel migrations
Mention any more fixes that i missed in the comments thanks.
Most of the time this kind of error occurs due to the datatype mismatch on both the table.
Both primary key table & foreign key table should use same datatype and same option.
For example:
users
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
orders
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('added_on');
});
On above example, I am trying to assign foreign key to users table from order table but I have bigInteger datatable in order table while in user table, I have simple integer. That's why it's generated this kind of error.
Also, If you have used unsigned(), nullable() etc options with primary or foreign key then you should use same at both the place.
For PHP laravel 5.8 use unsigned modifier in this format
$table->unsignedBigInteger('user_id');
drop all tables in the database and run the migration again
users
cashier refers users
student refers cashier
In addition when declaring foreign keys in laravel all tables your are referring must be on the top. In this case you can use "->unsigned()" modifier..
If the reference table primary key is in BigIcrements then Use the BigInteger for foreign key also like below
Table ATable
public function up()
{
Schema::create('a_tables', function (Blueprint $table) {
$table->bigIncrements('id');
}
}
TABLE BTable
public function up()
{
Schema::create('b_tales', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('a_tables_id')->unsigned();
$table->foreign('a_tables_id')->references('id')->on('a_tables')->onDelete('cascade');
}
}
public function up() { Schema::create('companies', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('address'); $table->string('tel1'); $table->string('tel2'); $table->integer('owner'); $table->unsignedBigInteger('access_id'); $table->string('depot_number')->default(2); $table->timestamps(); $table->foreign('access_id')->references('id')->on('accesses') ->onDelete('cascade'); }); }
public function up() { Schema::create('accesses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('type'); $table->string('description'); $table->timestamps(); }); }
In your database/migrations folder, sort by name. Then make sure create_accesses_table is before create_companies_table here:
we are table villes:
Schema::create('villes', function (Blueprint $table) {
$table->bigIncrements('idVille'); // bigIncrement(8 bits)
$table->string('nomVille');
$table->timestamps();
});
foreign key in table users for exemple :
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('ville_idVille')->unsigned()->after('tele');
$table->foreign('ville_idVille')->references('idVille')->on('villes');
});
if you set referencing fields and be have exactly the same data type but error exists
you can change date migration file
just its working
I tried all the answers provided in this thread.
Nothing worked.
Then I discovered I forgot to remove the "migrations" table in phpMyadmin.
I removed all tables from phpMyAdmin but the migrations table. That's why the error persisted again and again.
Well this answer is related to Laravel 7.x. So the error:
errno: 150 "Foreign key constraint is incorrectly formed"
can occur due many reason while migrating the migrations. The one common reason that I am familiar about is order of migration.
Lets say we have two table "users" and "roles", and "users" table have a foreign key referring the "id" column on "roles" table. So make sure that "roles" is migrated before "users" table.
So order of migration is important. Its obvious as it does not make sense for MySQL to refer to "id" column of unknown table.
Second reason is wrong data type. In laravel 7.x we use "id()" method for primary key. So make sure that the intended foreign key (in my case "role_id" in "users" table) is of "bigInteger" and is "unsigned".
Here my code:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->nullable();
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigInteger("role_id")->unsigned();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
public function down()
{
Schema::table('users', function(Blueprint $table)
{
$table->dropForeign('users_role_id_foreign');
});
Schema::dropIfExists('users');
}
So in the above code I had to migrate the "roles" table first then the "users" table. So MySQL can create foreign key for the roles table.
What is do is I move the child migration (migration having foreign key) to temporary folder. And restore it after migrating parent migration (in my case "roles" table and then migrate the child migration ("users" migration).
And as side tip: while dropping the dependent migration (migration containing foreign key) first drop the foreign key first. And Laravel uses specific naming convention while dropping foreign key "<table_name>_<foreign_key>_foreign".
So happy coding and be ready for Ground breaking release of PHP 8.
Here the main concept is you have to ensure same type of primary key and foreign key. For example, Let your 1st table migration is
public function up()
{
Schema::create('chapters', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
}
Then your 2nd table migration will be
public function up()
{
Schema::create('classifications', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('chapter_id');
$table->timestamps();
$table->foreign('chapter_id')->references('id')->on('chapters')->onDelete('cascade');
});
}
Here "id" in "chapter" table and "chapter_id" in " classifications " table are same and that is "unsignedBigInteger".
Again if you get error then change " $table->id(); " in "chapter" table by " $table->bigIncrements('id'); ".
Hope this will help you
for the laravel 7 migration error as
("SQLSTATE[HY000]: General error: 1005 Can't create table laraveltesting.reviews (errno: 150 "Foreign key constraint is incorrectly formed")")
order of migration is most important so parent table should be migrated first then only child
Image 1:migration order while getting error
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->float('price');
$table->integer('stock');
$table->float('discount');
$table->timestamps();
});
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
$table->string('customer');
$table->text('review');
$table->integer('star');
$table->timestamps();
});
this causes the error while migrating this can be resolved by changing the order of migration by renaming the migration as shown in image 2 from the image 1. books table should be migrated first then only the review table should be migrated
Image 2:Order of migration for the successful migration
if you get error change $table->id()(references) by $table->increments('id')
worked with me after all Efforts
delete (user table) from both database and (migration table) then "uncomment" your foreign key Relations
example :
$table->string('pass1');
$table->foreign('pass1')->references('email')->on('abs');
then run : php artisan migrate
well run successfully
sometime your query syntax is true but this error is occur because you create your table unorderly if you want to make relation between table let's suppose you wanna a create many to many relationship between "user" and "role" table for this you should migrate user and role table first then create "role_user" table else you face error like this.
For more details check my screenshot.
enter image description here
in laravel 9 i got same error while creating foreign key for my posts table
SQLSTATE[HY000]: General error: 1005 Can't create table `wpclone`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_author_id_foreign` foreign key (`author_id`) references `users` (`id`) on delete restrict)
and my table looks like this:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
});
after i found solution that in laravel 9 unsigned modifier in this format work well
$table->unsignedBigInteger('author_id');
and my error was solve. hope this will help you. Thanks

Laravel 5.1 foreign key migration error

I get this weird error when executing my constraints migration
When I execute this migration I get
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'flowtime_dev.#sql-85bb_52' (errno: 121) (SQL: alter table `questions` add constraint questions_inventory_i
d_foreign foreign key (`inventory_id`) references `inventories` (`id`) on delete cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'flowtime_dev.#sql-85bb_52' (errno: 121)
I've read that the data types in different tables should match ( like int(10) to int(10)) and they do, this is also the last migration that I have ( all the tables exist and have been created by other migrations before).
I seriously have no idea what to do anymore :(. Could someone help?
I have seen similar posts, but they have not fixed the problem so far for me.
The migration is as follows:
public function up()
{
Schema::table('questions', function ($table) {
$table->integer('inventory_id')->unsigned()->change();
$table->foreign('inventory_id')
->references('id')->on('inventories')
->onDelete('cascade');
});
Schema::table('question_response', function ($table) {
$table->integer('question_id')->unsigned()->change();
$table->foreign('question_id')
->references('id')->on('questions')
->onDelete('cascade');
});
Schema::table('question_response', function ($table) {
$table->integer('sample_result_set_id')->unsigned()->change();
$table->foreign('sample_result_set_id')
->references('id')->on('sample_response_set')
->onDelete('cascade');
});
Schema::table('inventory_response', function ($table) {
$table->integer('inventory_id')->unsigned()->change();
$table->foreign('inventory_id')
->references('id')->on('inventories')
->onDelete('cascade');
});
Schema::table('inventory_response', function ($table) {
$table->integer('sample_result_set_id')->unsigned()->change();
$table->foreign('sample_result_set_id')
->references('id')->on('sample_response_set')
->onDelete('cascade');
});
}
In the beginning of your migration turn off foreign key constraints.
SET FOREIGN_KEY_CHECKS=0;
Then, when the data is migrated, turn them back on.
SET FOREIGN_KEY_CHECKS=1;
If that doesn't work, then try adding the following line.
$table->engine = 'InnoDB'
Further, you can rename the constraint since the name may already be used...
$table->foreign('inventory_id', 'fk_questions_inventory_id')->...
Try to use two separate migrations.
Create first migration, which will create tables and all columns (put everything except $table->foreign clauses here). Run migrate command. Do not execute second one, temporarily remove it from migrations directory, if you've already have this migration.
Then create second migration, which will add foreign keys to already created columns (use only $table->foreign clauses here). Run migrate command again.
This helped me, when I was in the same situation. I hope it will work for you too.

Categories