Laravel migration: integrity constraint violation - laravel

I get an error whenever I try to insert values into this table.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(usersexam.role_user, CONSTRAINT role_user_role_id_foreign
FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE)
Here is the migration for that table in my Laravel's database folder:
class CreateRoleUserPivotTable extends Migration
{
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->references('id')->on('roles')
->cascadeOnDelete();
$table->foreignId('user_id')->references('id')->on('users')
->cascadeOnDelete();
});
}
public function down()
{
Schema::dropIfExists('role_user');
}
}
So I am inserting it into two columns. What is wrong with the table?
UPDATE: here is my insert query

when ever ur creating a tables and refrense a foreign key u still need to make the columns so instead of
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->references('id')->on('roles')->cascadeOnDelete();
$table->foreignId('user_id')->references('id')->on('users')->cascadeOnDelete();
});
it should be something like
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedInteger('role_id');
$table->unsignedInteger('user_id');
$table->foreign('role_id')
->references('id')
->on('roles')
->cascadeOnDelete();
$table->foreign('user_id')
->references('id')
->on('users')
->cascadeOnDelete();
});

Related

Migration: Cannot add foreign key constraint - Laravel 9

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');

Laravel migration fails with SQLSTATE[HY000]: General error: 1215

I'm trying to add a migration with laravel. This is mi migration file.
public function up() {
Schema::create('sl_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->softDeletes();
$table->timestamps();
});
Schema::create('sl_images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image')->nullable();
$table->integer('sl_category_id')->unsigned()->nullable();
$table->integer('display_order')->nullable();
$table->softDeletes();
$table->timestamps();
});
Schema::table('sl_images', function(Blueprint $table) {
$table->foreign('sl_category_id')->references('id')->on('sl_categories')->onDelete('cascade');
});
}
public function down() {
Schema::dropIfExists('sl_images');
Schema::dropIfExists('sl_categories');
}
But unfortunately I'm getting this error.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error:
1215 Cannot add foreign key constraint (SQL: alter table sl_images
add constraint sl_images_sl_category_id_foreign foreign key
(sl_category_id) references sl_categories (id) on delete
cascade)
Finally I found the answer. The issue is InnoDB does not permit the creation of a foreign key constraint where a column references a nonmatching column type. If simply said,
This is a big integer
$table->bigIncrements('id');
and this is a simple integer.,
$table->integer('sl_category_id')->unsigned()->nullable();
So we have to change the later line to bigInteger,
$table->bigInteger('sl_category_id')->unsigned()->nullable();
I'm adding this answer in case someone else will find some use of it.

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');

Cannot find Foreign key constraint index

my run_tasks table has foreign key completer_guest_id which I need to refer to some other table's column.
Schema::table('run_tasks', function (Blueprint $t) {
$t->integer('completer_id')->nullable();
$t->foreign('completer_id')->references('id')->on('users');
$t->integer('completer_guest_id')->nullable();
$t->foreign('completer_guest_id')->references('id')->on('tasks_guests');
});
But I cannot find the index: run_tasks_completer_guest_id_foreign
because of which I cannot drop the foreign key constraint and delete the column in this migration:
Schema::table('run_tasks', function (Blueprint $table){
$table->dropForeign('run_tasks_completer_guest_id_foreign');
$table->dropColumn('completer_guest_id');
$table->integer('completer_guest_id')->nullable();
$table->foreign('completer_guest_id')
->references('id')
->on('guests')
->onDelete('cascade');
});
and I am getting this error, When I run \d run_tasks I see this
Is there any workaround for this problem?
drop the table and try to separate the creation and the foreign keys assignment
Schema::dropIfExists('run_tasks');
Schema::create('run_tasks', function (Blueprint $table) {
$table->integer('completer_id')->nullable();
$table->integer('completer_guest_id')->nullable();
$table->index(['completer_id', 'completer_guest_id']);
});
Schema::table('run_tasks', function(Blueprint $table) {
$table->foreign('completer_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('completer_guest_id')->references('id')->on('guests')->onDelete('cascade');
});

Error in adding foreign key in laravel

I am beginner in laravel. I am having problem in adding foreign key in laravel. I tried but I can't find the error.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table laravel_home1
#sql-4b8_2a (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table `posts` add constraint
`posts_comment_id_foreign` foreign key (`comment_id`) references
`comments` (`id`))
post table migration code
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->integer('comment_id')->unsigned();
});
Schema::table('posts', function ($table) {
$table->foreign('comment_id')
->references('id')
->on('comments');
});
}
comments table migration code
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('comment');
$table->timestamps();
});
}
public function down()
{
Schema::drop('comments');
}
Problems with adding foreign key in laravel come with 3 reasons:
You have already done some rollbacks or migrated the same migration file multiple times and they are saved in cache and thus causing the problem
You forgot to put ->unsigned(); at the end of that index.
The table with primary key which is later used elsewhere as a foreign key is not migrated previously.
Either way try to put ->unsigned(); at the end like this
$table->integer('item_id')->unsigned();
$table->foreign('item_id')->references('id')->on('items');
and then run composer dump-autoload
and then php artisan migrate
and this should work!
UPDATE
I have found what is wrong with your migration:
Replace this:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->integer('comment_id')->unsigned();
});
Schema::table('posts', function ($table) {
$table->foreign('comment_id')
->references('id')
->on('comments');
});
}
With this:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->integer('comment_id')->unsigned();
$table->foreign('comment_id')
->references('id')
->on('comments');
});
}

Resources