(Resolved) Laravel 6.2 : adding foreign key constraint failed during migration - mysql

I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_ent_id_foreign` foreign key (`ent_id`) references `id_ent` (`entreprises`))
My migration code for 'Entreprises'
public function up()
{
Schema::create('entreprises', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id_ent');
$table->string('name');
$table->string('numSiret', 14)->unique();
$table->integer('nbr_couvert')->length(10);
$table->timestamps();
});
}
My migration code for 'Users'
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id_user');
$table->string('log');
$table->string('name', 45);
$table->string('firstName', 45);
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->string('num_phone', 20);
$table->datetime('created_at');
$table->unsignedInteger('ent_id');
$table->integer('agenda_id')->nullable();
$table->tinyInteger('droitUser')->nullable();
$table->boolean('validateMail');
$table->string('key', 255);
});
Schema::table('users', function ($table) {
$table->foreign('ent_id')
->references('entreprises') //here
->on('id_ent'); //and here
});
I change the order of the migrations and the table 'entreprises' are create before the 'users' table.
I tried every solutions from here and here and they are nothing to change.
Any suggestions someone ?
Editing for solution
Shame on me... I just do a stupid mistake when I reference the table I wanted to reference... Everything is fine now... Sorry

Are you using sqlite database? if so sqlite database by default disabled foreign key feature.
SQLite disables foreign key constraints by default. When using SQLite, make sure to enable foreign key support in your database configuration before attempting to create them in your migrations.
you can check here to enable foreign key in sqlite database.

Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->string('title');
$table->string('slug')->unique();
$table->string('image')->default('default.png');
$table->string('zip');
$table->text('body');
$table->integer('view_count')->default(0);
$table->boolean('status')->default(false);
$table->boolean('is_approved')->default(false);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();

Related

foreign key references a composite primary key in laravel

I made a create table migration like this:
Schema::create('judgments', function (Blueprint $table) {
$table->bigIncrements('judgment_id')->unique();
$table->unsignedBigInteger('virtual_member_id');
$table->unsignedBigInteger('member_id');
$table->unsignedBigInteger('form_id');
$table->integer('judgement')->range(0,101); // give a number between 0 to 101 to give a judge
$table->timestamps();
});
and then I made another migration (add_foreign_key_to_judgments) like this:
Schema::table('judgments', function (Blueprint $table) {
$table->foreign('virtual_member_id')->references(['virtual_id','employee_id'])->on('virtual_members')->onDelete('cascade');
});
I also tried to make (add_foreign_key_to_judgments) migration like this:
Schema::table('judgments', function (Blueprint $table) {
$table->foreign('virtual_member_id')->references('virtual_member_id')->on('virtual_members')->onDelete('cascade');
});
where virtual_members migration is :
Schema::create('virtual_members', function (Blueprint $table) {
$table->unsignedBigInteger('virtual_id');
$table->unsignedBigInteger('employee_id');
$table->foreign('virtual_id')->references('virtual_id')->on('virtuals')->onDelete('cascade');
$table->foreign('employee_id')->references('employee_id')->on('employees')->onDelete('cascade');
$table->primary(['virtual_id','employee_id'],'virtual_member_id')->unique();
$table->timestamps();
});
I got this error when I run php artisan migrate:
SQLSTATE[42000]: Syntax error or access violation: 1239 Incorrect foreign key definition for 'judgments_virtual_member_id_foreign': Key reference and table reference don't match (SQL: alter table `judgments` add constraint `judgments_virtual_member_id_foreign` foreign key (`virtual_member_id`) references `virtual_members` (`virtual_id`, `employee_id`) on delete cascade)

Laravel Migration Error "Cannot add foreign key constraint" [duplicate]

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 migration error while adding 2 foreign key

I am using Laravel migrations to create my MySQL database, and have two tables papers and answers, and need to connect both tables using foreign keys. I have the paper_id as well as question_no as the foreign keys. but when adding foreign key I get an error.
My migration for paper table and answer table
Schema::create('exampapers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper_id');
$table->integer('question_no');
$table->text('question');
$table->string('answer1');
$table->string('answer2');
$table->string('answer3');
$table->string('answer4');
$table->integer('answerC');
$table->string('knowarea');
$table->timestamps();
$table->index(['paper_id','question_no']);
});
Schema::create('answers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper')->unsigned();
$table->integer('question')->unsigned();
$table->integer('answers');
$table->timestamps();
});
and this is my code for creating foreign keys,
Schema::table('answers',function($table){
$table->foreign('paper')->references('paper_id')->on('exampapers');
$table->foreign('question')->references('question_no')->on('exampapers');
});
The error I get through php artisan is,
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error:
1005
Can't create table exam_paper.#sql-b88_630 (errno: 150 "Foreign key
constraint is incorrectly formed") (SQL: alter table answers add
constraint answers_paper_foreign
foreign key (paper) references exampapers (paper_id))
I referred most of the other posts and already tried unsignedInteger() data type, running the table creation before foreign key creation.
What am I doing wrong in my code?
You need to add ->unsigned()->nullable()->index(); in both column (i.e. in paper_id and in question in exampapers table).
Try to add like below in exampapers table:
$table->integer('paper_id')->unsigned()->nullable()->index();
$table->integer('question_no')->unsigned()->nullable()->index();
Now run php artisan migrate and problem fixed!
Hope this helps you!
You need to make the key in the exampapers table unsigned too:
$table->integer('paper_id')->unsigned();
Or:
$table->insignedInteger('paper_id');
Or remove the unsigned() method from the foreign key definition:
$table->integer('paper');
I have made some edits to your migration code. Hope this will work
Schema::create('exampapers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper_id')->unsigned()->index();
$table->integer('question_no')->unsigned()->index();
$table->text('question');
$table->string('answer1');
$table->string('answer2');
$table->string('answer3');
$table->string('answer4');
$table->integer('answerC');
$table->string('knowarea');
$table->timestamps();
//$table->index(['paper_id','question_no']);
});
Schema::create('answers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper')->unsigned()->index();
$table->integer('question')->unsigned()->index();
$table->integer('answers');
$table->timestamps();
});
Schema::table('answers',function($table){
$table->foreign('paper')->references('paper_id')->on('exampapers');
$table->foreign('question')->references('question_no')->on('exampapers');
});

Laravel: how to import a sql file through phpmyadmin after you created a schema without throwing a constraint exception?

Hi I have the following schema code:
public function up()
{
Schema::create('states', function(Blueprint $table)
{
$table->increments('id');
$table->string('acronym');
$table->string('name');
});
Schema::create('cities', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('states');
});
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('fullname');
$table->string('photo');
$table->text('description');
$table->string('email')->unique();
$table->string('password', 60);
$table->integer('city_id')->unsigned();
$table->foreign('city_id')->references('id')->on('cities');
$table->rememberToken();
});
}
public function down()
{
Schema::drop('states');
Schema::drop('cities');
Schema::drop('users');
}
The migration works fine, now I want to import a sql file through phpmyadmin, but I receive the following error:
1452 - Cannot add or update a child row: a foreign key constraint fails (yearbook.cities, CONSTRAINT cities_state_id_foreign FOREIGN KEY (state_id) REFERENCES states (id))
Before making the migration it worked fine, so I'd like to know if there is a way to import the file without removing the foreign keys.
Thanks in advance.
Your migration is fine and the problem is in your data.
Since you have added foreign key constraint then state with this id must exist before you can import cities.
Right now you have states id autoincrementing so you need to overwrite it or be absolutely sure it gets correct ID from insert order.

SQLSTATE[23000]: Integrity constraint violation: 1217

After creatin multiple migrations in my project, I wanted to rollback to update a few things but suddenly I got this error when I tried to drop projects table. I double checked the foreign key constrains but I can't find the error.
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or upda
te a parent row: a foreign key constraint fails (SQL: drop table `projects`
)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or upda
te a parent row: a foreign key constraint fails
Here are my migrations:
1.create table users:
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email', 50)->unique();
$table->string('password', 60);
$table->string('password_temp', 60);
$table->string('code', 60);
$table->boolean('active');
$table->string('remember_token', 100);
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
2.create clients table:
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned()->index()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop('clients');
}
3.create projects table:
public function up()
{
Schema::create('projects', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->integer('status');
$table->integer('client_id')->unsigned()->index()->nullable();
$table->foreign('client_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop('projects');
}
In the last migration, what could possibly be the mistake I am doing?! I face no trouble when migrating but it appears only when I rollback to add any changes.
Any idea why this happens?
Use this in down function.
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('tableName');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
If there are only 3 tables above mentioned, there is no issue in your migration as I have tried it myself with
php artisan migrate
to create the tables and
php artisan migrate:rollback
to rollback.
One thing that I know is Laravel is going to assume the sequence of the migration based on the migration file timestamp.
Therefore, I am quite sure there is another table that has a foreign key reference to the projects tables that has not been dropped as the error messsage is (SQL: drop table projects)
Try to use php artisan tinker and then Schema::drop('some_table_name'); where some_table_name is the table that has reference to projects table, then drop the projects table again.
When you use foreign keys in your tables you need to remove those using the dropForeign method before you drop your table, else you will run into the integrity constraint issues you are currently getting.
public function down()
{
Schema::table('projects', function(Blueprint $table) {
$table->dropForeign('projects_client_id_foreign');
});
Schema::drop('projects');
}
This problem is commonly created by editing/adding to existing migrations.
Either create new migration files when dealing with foreign keys or be prepared to potentially dump/drop your entire db and refresh.