Laravel make migration with foreign key failed - laravel

I have a project named Partner
I need to create developers table and two other tables branches and projects
And every Developer has many branches and has many projects
So I created this migration files:
Developers
public function up()
{
Schema::create('developers', function (Blueprint $table) {
$table->id();
$table->string('company_name', 100);
$table->string('responsible_name', 100);
$table->string('email', 100);
$table->string('phone', 100);
$table->string('hotline', 100)->nullable();
$table->timestamps();
});
}
Branches
public function up()
{
Schema::create('branches', function (Blueprint $table) {
$table->id();
$table->integer('developer_id')->unsigned();
$table->string('name', 100);
$table->string('address', 100);
$table->string('location', 100);
$table->string('phone', 100);
$table->timestamps();
$table->foreign('developer_id')->references('id')->on('developers')->onDelete('cascade');
});
}
Projects
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->integer('developer_id')->unsigned();
$table->string('name', 100);
$table->string('type', 100);
$table->string('address', 100);
$table->string('location', 100);
$table->string('availability', 100);
$table->text('payment_plan');
$table->string('brochure', 100)->nullable();
$table->timestamps();
$table->foreign('developer_id')->references('id')->on('developers')->onDelete('cascade');
});
}
But when I ran php artisan migrate I got this error
SQLSTATE[HY000]: General error: 1005 Can't create table `partner`.`branches` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `branches` add constraint `branches_developer_id_foreign` foreign key (`developer_id`) references `developers` (`id`) on delete cascade)
What is the wrong with the form of the foreign key?

You can use foreign key in migration without predefine field :
$table->foreignId('developer_id')->constrained('developers')->onDelete('cascade');
and remove this line :
$table->integer('developer_id')->unsigned();

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

How to add foreign key in laravel migration?

I have an employer_profiles table, a job_posts table and an employer_profile_job_post table. I'm trying to make a relationship and add the foreign keys but I keep getting this error and I'm not sure why.
SQLSTATE[HY000]: General error: 1005 Can't create table `highrjobsadminlte`.`employer_profile_job_post` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `employer_profile_job_post` add constraint `employer_profile_job_post_job_post_id_foreign` foreign key (`job_post_id`) references `job_posts` (`id`))
create_employer_profile_job_post_table.php:
public function up()
{
Schema::create('employer_profile_job_post', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('employer_profile_id')->unsigned()->index();
$table->bigInteger('job_post_id')->unsigned()->index();
$table->timestamps();
$table->foreign('employer_profile_id')->references('id')->on('employer_profiles');
$table->foreign('job_post_id')->references('id')->on('job_posts');
});
}
create_employer_profiles_table.php:
public function up()
{
Schema::create('employer_profiles', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->index()->unsigned();
$table->string('company_name');
$table->string('phone',30)->nullable();
$table->string('street');
$table->string('city', 50);
$table->string('country', 80);
$table->string('zip_postal', 25);
$table->string('province_state', 50);
$table->string('number_of_employees');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
create_job_posts_table.php:
public function up()
{
Schema::create('job_posts', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->index()->unsigned();
$table->bigInteger('employer_profile_id')->index()->unsigned();
$table->string('job_title');
$table->longText('job_description');
$table->string('salary', 20);
$table->string('employment_type', 20)->nullable();
$table->string('location_name', 100);
$table->tinyInteger('is_active')->default(0);
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('employer_profile_id')->references('id')->on('employer_profiles');
});
}

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

I'm executing the command at the terminal getting this error to build the product table

I'm creating a products table in my Laravel application
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->integer('price');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users');
});
}
Afterwards, I'm trying to migrate my database
$ php artisan migrate
However, I'm getting this error when migrating the products table:
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `apps`.`#sql-30d4_61` (errno: 150 "Foreign key constraint is incorrectly formed")")
C:\xampp\htdocs\LTCRUDAUT\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
2 PDOStatement::execute()
C:\xampp\htdocs\LTCRUDAUT\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
How would I fix it?
This is probably because Laravel now uses bigIncrements() instead of increments() by default for the id field in the user table migration.
For foreign keys, they have to be set to the same field size. To fix:
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('user_id')->unsigned();
$table->string('name');
$table->integer('price');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users');
});
}

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