Migration: Cannot add foreign key constraint - Laravel 9 - laravel

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: 1005 Can't create table `bright`.`carts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `carts` add constraint `carts_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)
My migration code is as so: carts migration file
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('product_id')->unsigned();
$table->integer('customer_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->string('quantity');
});
}
products migration file
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('unit');
$table->decimal('price', 6, 3);
$table->string('img_url');
$table->string('description');
$table->integer('sold');
$table->integer('in_stock');
});
}
customers migration file
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('phone_number');
$table->string('address');
$table->string('zip')->nullable();
$table->string('email')->unique();
$table->string('user_name')->unique();
$table->string('password');
});
}
Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. carts, products, customers. Ideally I want to create carts table which hold this data with the foreign keys, i..e product_id and cart_id

Try using this structure.
$table->foreignIdFor(Product::class);
$table->foreign('product_id')->references('id')->on('products');
$table->foreignIdFor(Customer::class);
$table->foreign('customer_id')->references('id')->on('customers');
Also make sure, your products and customers migrations run before your carts migrations, and your models are imported to your migrations.

You can use like this.
$table->unsignedBigInteger('product_id')->nullable();
$table->foreign('product_id')->references('id')->on('products');
$table->unsignedBigInteger('customer_id')->nullable();
$table->foreign('customer_id')->references('id')->on('customers');

Related

Add laravel migrations with foreign keys

I have created a table called 'users'.There are tables called 'companies','designations','departments'.I want to add company_id,designation_id,department_id columns to users table as foreign keys.
I tried this but it didn't work
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('department_id');
$table->integer('company_id');
$table->integer('designation_id');
$table->foreign('department_id')->references('id')->on('departments')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('designation_id')->references('id')->on('designations')->onDelete('restrict')->onUpdate('restrict');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['department_id','company_id','designation_id']);
});
}
When I migrate the migration it shows this error.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1005 Can't create table lanwadb.users (errno: 150 "Foreign
key constraint is incorrectly formed") (SQL: alter table users add
constraint users_department_id_foreign foreign key (department_id)
references departments (id) on delete restrict on update restrict)
Designation migration as follows,
public function up()
{
Schema::create('designations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestampsTz();
});
}
Department migration as follows,
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('company_id');
$table->timestampsTz();
});
}
```
To make relationship the foreign key field should be indexed. Here you have three columns you want to use as foreign key 'company_id', 'department_id' and 'designation_id'. In Laravel migration you can use unsigned() function to index them.
Example:
$table->integer('department_id')->unsigned();
$table->integer('company_id')->unsigned();
$table->integer('designation_id')->unsigned();
There is another function called unsignedInteger() by which you can make a column both Integer and Unsigned.
$table->unsignedInteger('department_id');
$table->unsignedInteger('company_id');
$table->unsignedInteger('designation_id');
use this:
$table->integer('department_id')->unsigned()->nullable();
$table->integer('company_id')->unsigned()->nullable();
$table->integer('designation_id')->unsigned()->nullable();
$table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('company_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('designation_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');

Foreign Key problem when migrating migrations in laravel 5.6

Am working on a Laravel 5.6 application whereby I have 2 tables mainly sponsors table and children table. Am creating a one to many relationship between the tables before migrating them. A child may have many sponsors.
The problem is I get this error when migrating them using php artisan migrate command:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error:
1005 Can't create table larangular.#sql-520c_21f (errno: 150
"Foreign key constraint is incorrectly formed") (SQL: alter table
sponsors add constraint sponsors_child_id_foreign foreign key
(child_id) references children (id) on delete cascade)
Sponsors migration
public function up()
{
Schema::create('sponsors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('child_id')->unsignedInteger();
$table->foreign('child_id')->references('id')->on('children')->onDelete('cascade');
$table->foreign('child_id')->references('id')->on('children');
$table->string('email')->unique();
$table->string('phone');
$table->string('nationality');
$table->timestamps();
});
}
Children migration
public function up()
{
Schema::create('children', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('age');
$table->string('gender');
$table->timestamps();
});
}
Make sure that your children migration runs before your sponsors migration, and then the column should be this:
$table->unsignedInteger('child_id');
// or
$table->integer('child_id')->unsigned();
unsignedInteger is a function that creates a column, you should not call it on an existing column.
// This creates an unsigned integer column.
$table->unsignedInteger('child_id');

laravel errno: 150 "Foreign key constraint is incorrectly formed

I user below tutorial for laravel categories :
Laravel categories with dynamic deep paths
I use below code same tutorial for migration :
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug');
$table->integer('parent_id')->unsigned()->default(0);
$table->timestamps();
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
});
}
but I have below error :
SQLSTATE[HY000]: General error: 1005 Can't create table 'xxx'.'#sql-453_147' (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'categories' add constraint 'categories_parent_id_foreign' foreign key ('parent_id') references 'categories' ('id') on delete cascade on update cascade)
Thanks for help
When creating a new table in Laravel. A migration will be generated like:
$table->bigIncrements('id');
Instead of (in older Laravel versions):
$table->increments('id');
When using bigIncrements the foreign key expects a bigInteger instead of an integer. So your code will look like this:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug');
$table->bigInteger('parent_id')->unsigned()->default(0);
$table->timestamps();
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
});
}
The problem is because of the difference of the column types. So unlike the tutorial you are using bigIncrements which means big integer for the ID and using the default integer for the parent_id. Try changing the id to this:
$table->increments('id');
or your parent_id to this:
$table->bigInteger('parent_id')->unsigned()->default(0);

Foreign Key makes Problems in Laravel 5.6

I would like to program an inventory system and need 3 tables for it. These can also be generated via artisan without a foreign key. But as soon as I want to add a foreign key, I get the following error message.
SQLSTATE[HY000]: General error: 1005 Can't create table `inventar`.`#sql-fd4_141` (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table items add constraint items_lend_foreign foreign key (lend) references lending (id))
Here my Code:
Item Table
Schema::create('items', function (Blueprint $table) {
$table->string('barcode');
$table->primary('barcode');
$table->string('name');
$table->string('description')->nullable();
$table->string('room')->nullable();
$table->string('status')->nullable();
$table->string('annotation')->nullable();
$table->string('image')->nullable();
$table->integer('lend')->unsigned()->nullable();
$table->string('manufactor')->nullable();
$table->timestamps();
});
Schema::table('items',function ($table){
$table->foreign('lend')->references('id')->on('lending');
});
Lending Table
Schema::create('lending', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('personid')->unsigned();
$table->dateTime('startdate');
$table->dateTime('enddate');
$table->timestamps();
});
Schema::table('lending',function ($table){
$table->foreign('barcode')->references('barcode')->on('items');
$table->foreign('personid')->references('personid')->on('persons');
});
Persons-Table
Schema::create('persons', function (Blueprint $table) {
$table->integer('personid')->unsignd()->primary();
$table->string('firstname');
$table->string('lastname');
$table->string('email');
$table->string('annotation')->nullable();
$table->timestamps();
});
I've also googled, but found no solution that works for me.
Is it a problem that my primary key is a string?
Your problem comes in the line
Schema::create('persons', function (Blueprint $table) {
$table->integer('personid')->unsignd()->primary();
}
Change it to unsigned() from unsignd() and it will work fine.

Many to Many on Laravel migration

I have 3 tables to connect each other. Tables name's roles, role_user, and users. I want to make migration on laravel and adding some constraint. and here's what in my role tables migration:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
and here's my Users table migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('active')->default(0);
$table->softDeletes();
$table->rememberToken();
$table->timestamps();
});
and here's my role_user table migration:
Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->unique(['role_id', 'user_id']);
$table->foreign('role_id')->references('id')->on('roles')
->onDelete('cascade')->onUpdate('cascade');
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')->onUpdate('cascade');
});
in my Migration order i put roles table on top of users already but i got this kind of errors:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `role_user` add constraint `role_user_role_id_foreign` foreign key (`role_id
`) references `roles` (`id`) on delete cascade on update cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Probably your problem was with the order of creation of migrations.
Laravel runs the migrations in order of creation using the timestamp in the file name , because of that, if you created them in the following order:
roles in 2018_06_02_023539_create_roles_table
role_user in 2018_06_02_023800_create_role_user_table
users in 2018_06_02_023815_create_users_table
The table users would not exist when referenced in the table role_user, thus causing an SQL error.
The most simple fix that you could do is renaming the role_user migration file in this way:
2018_06_02_023800_create_role_user_table => 2018_06_02_023820_create_role_user_table
Try this one on the pivot table
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
I delete all my table and left just 4 tables :
create_user_table,
create_password_reset,
create_roles_table,
create_role_user
and everything works fine.
Till now I don't understand what makes these errors although I already put the same orders.
in table "role_user" replace columns type from integer to bigIncrements

Resources