Error in adding foreign key in laravel - 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');
});
}

Related

Foreign key constraint is incorrectly formed in laravel 7

I am building a hotel management application using laravel. I am trying to create the tables 'reservations' in laravel but when I run the 'migrate:fresh' command, I get the following: error "Foreign key constraint is incorrectly formed". Can anyone tell what do you mean by this error?
View Error
public function up()
{
Schema::create('room_types', function (Blueprint $table) {
$table->id();
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('short_code')->unique();
$table->longText('description')->nullable();
$table->integer('base_capacity')->default(0);
$table->integer('higher_capacity')->default(0);
$table->boolean('extra_bed')->default(0);
$table->integer('kids_capacity')->default(0);
$table->float('base_price',8,2)->default(0);
$table->float('additional_person_price',8,2)->default(0);
$table->float('extra_bed_price',8,2)->default(0);
$table->boolean('status')->default(1);
$table->softDeletes();
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('usertype')->default('user');
$table->string('last_name')->nullable();
$table->string('phone')->nullable();
$table->date('dob')->nullable();
$table->longText('address')->nullable();
$table->enum('sex',['M','F','O'])->default('M');
$table->string('picture')->nullable();
$table->string('id_type')->nullable();
$table->string('id_number')->nullable();
$table->string('id_card_image_front')->nullable();
$table->string('id_card_image_back')->nullable();
$table->string('company_name')->nullable();
$table->string('gst_no')->nullable();
$table->text('remarks')->nullable();
$table->boolean('vip')->default(0);
$table->boolean('status')->default(1);
$table->rememberToken();
$table->timestamps();
});
}
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedInteger('user_id');
$table->unsignedInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}
Error message
SQLSTATE[HY000]: General error: 1005 Can't create table `hotelplex`.`reservations` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `reservations` add constraint `reservations_reservations_user_id_foreign` foreign key (`reservations_user_id`) references `users` (`id`) on delete cascade)
at C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `hotelplex`.`reservations` (errno: 150 "Foreign key constraint is incorrectly formed")")
2 C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
Laravel6
Laravel6 does not have any method id() to create id in a table. Laravel7 does.. I tried creating id using $table->id() using Laravel6 and got the below error.
It seems you posted wrong error or you have already created id manually in your tables.
You can use bigIncrements,bigInteger, increments,integer etc.
You can find all available methods here
Laravel7
As per Laravel7 $table->id() is alias of Alias of $table->bigIncrements('id') i.e. unsigned big integer.
To create Foreign key the data type for the child column must match the parent column exactly.
Since users.id and room_types.id is a bigIncrements then reservations.user_id and reservations.room_type_id also needs to be an unsignedbigInteger, not a unsignedInteger.
So to make it work
change
$table->unsignedInteger('user_id');
$table->unsignedInteger('room_type_id');
to
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
Like this:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}
https://laravel.com/docs/7.x/migrations#creating-columns
The problem seems to be of data type mismatching for user_id and room_type_id
$table->id(); alias of Alias of $table->bigIncrements('id');
https://laravel.com/docs/master/migrations#columns
So, you need foreign user_id and room_type_id column on reservations like:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
// Structure
$table->id();
...
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
...
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
...
})
}
on laravel 8, you can use this
$table->id();
....
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
...
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('restrict');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('restrict');
The ->onDelete('cascade'); should be on the relationships creation part.
Change the to:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
// Structure
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
// Relationships
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}

Laravel 5.8 error SQLSTATE[HY000]: General error: 1005 uuid

I am using Laravel 5.8 and package "goldspecdigital/laravel-eloquent-uuid" because I need to use UUID4 and here is my migration file:
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
// $table->timestamps();
$table->string('path');
$table->uuid('visit_id');
$table->foreign('visit_id')->references('id')->on('visits');
});
}
I get the following error:
SQLSTATE[HY000]: General error: 1005 Can't create table doctors
_pharmacy.images (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table images
add constraint images_visit_id_foreign foreign key (visit_id) references visits (id))
How do I solve this?
Update the schema for visits and images as follows.
Then run php artisan migrate cmd.
visits table schema
public function up()
{
Schema::create('visits', function (Blueprint $table) {
$table->uuid('id')->primary();
// your column will be here
......
......
$table->timestamps();
});
}
images table schema
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('path');
$table->uuid('visit_id');
$table->foreign('visit_id')->references('id')->on('visits');
});
}

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

laravel migration "SQL: alter table `posts` add constraint `posts_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) "

am trying to do laravel migration but am getting this error
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `urbancruise`.`#sql-18f8_112` (errno: 150 "Foreign key cons
traint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_category_id_foreign` foreign key (`c
ategory_id`) references `categories` (`id`))
here is my code
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down(){
Schema::drop('categories');
}
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}
public function down(){
Schema::drop('posts');
}
When you are creating a foreign key, the categories.id and posts.category_id must have the same type.
Swap the ->bigInteger() with ->integer()should solve your problem:
Your categories migration:
public function up(){
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down(){
Schema::drop('categories');
}
In your posts migration:
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id', false, true);
//Or $table->unsignedInteger('category_id');
$table->foreign('category_id')
->references('id')
->on('categories');
$table->timestamps();
});
}
public function down(){
Schema::drop('posts');
}
Hope it helps.
Foreign key should always be of same type in both child and parent table.
In your case, categories.id is of type ٰINTEGER while posts.category_id is defined as BIGINT. Replacing your posts migration with below should work.
public function up() {
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}

Laravel Migration: auto incremented id as foreign key "errno: 150 "Foreign key constraint is incorrectly formed""

I was trying to migrate in Laravel with foreign key that points to the auto incremented id of debiturs table:
public function up()
{
Schema::create('debitur', function (Blueprint $table) {
$table->increments('id');
$table->string('nama');
$table->string('email')->unique();
$table->timestamps();
});
}
But when I tried adding a foreign key below, it throws a "150 Foreign Key constraint is incorrectly formed" error.
public function up()
{
Schema::create('tempat_tinggal', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_debitur')->unsigned();
});
Schema::table('tempat_tinggal', function ($table) {
$table
->foreign('id_debitur')
->references('id')
->on('debiturs')
->onDelete('cascade')
->onUpdate('cascade');
});
}
I have tried deleting the database and starting from scratch, but it still throws the same error. I must be missing something...
EDIT: for some reason Laravel does not automatically append 's' to 'debitur' when creating table.
$table
->foreign('id_debitur')
->references('id')
->on('debitur') <-------
->onDelete('cascade')
->onUpdate('cascade');
Your code is looking fine may be you have a some data in your table which does not reffering to the reffered table.
public function up()
{
Schema::create('tempat_tinggal', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('id_debitur');
});
Schema::table('tempat_tinggal', function ($table) {
$table
->foreign('id_debitur')
->references('id')
->on('debiturs')
->onDelete('cascade')
->onUpdate('cascade');
});
}

Resources