Can't make migration to Laravel SQLSTATE[42703] - laravel

I keep getting an error when trying to do a database migration
SQLSTATE[42703]: Undefined column: 7 ERROR: column "user_id" referenced in foreign key constraint does not exist (SQL: alter table "ads" add constraint "ads_user_id_foreign" foreign key ("user_id") references "users" ("id"))
This is my migration file
public function up()
{
Schema::create('ads', function (Blueprint $table) {
$table->id();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('city_id')->references('id')->on('cities');
$table->string('title');
$table->text('description');
$table->text('photos');
$table->string('status');
$table->timestamps();
});
}

You need first to create the columns before add foreign key
public function up()
{
Schema::create('ads', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('city_id');
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('city_id')->references('id')->on('cities');
$table->string('title');
$table->text('description');
$table->text('photos');
$table->string('status');
$table->timestamps();
});
}

Related

Laravel 7 General error: 1215 Cannot add foreign key constraint

I've been researching this for hours, can't seem to solve it. Here is the error
General error: 1215 Cannot add foreign key constraint (SQL: alter table 'users' add constraint 'users_discord_id_foreign' foreign key ('discord_id') references 'discord_o_auths' ('id'))
Here is my DiscordOAuths Migration:
public function up()
{
Schema::create('discord_o_auths', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->integer('id')->unique();
$table->string('access_token')->unique();
$table->string('refresh_token')->unique();
$table->bigInteger('token_expiration');
$table->timestamps();
});
}
And here is my Users Migration.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->boolean('admin')->default(false);
$table->integer('color_scheme')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->engine = "InnoDB";
$table->integer('discord_id')->unsigned();
$table->foreign('discord_id')->references('id')->on('discord_o_auths');
});
}
The DiscordOAuths table is created before the Users table as well. What am I doing wrong?
You're trying to assign a foreign key constraint to an integer column, which is not the same as the unsigned columns that Laravel uses for its id's.
In your DiscordOAuths you have to replace $table->integer('id')->unique(); with $table->bigIncrements('id'); or the new method added in Laravel 7 $table->id(); which is an alias of the previous one.
Your discord_id column in the users migration also needs to be an unsigned column. You have to define it using either $table->unsignedBigInteger('discord_id'); or its alias that came with Laravel 7: $table->foreignId('discord_id');
So your migrations would look like this:
For DiscordOAuths
public function up()
{
Schema::create('discord_o_auths', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->string('access_token')->unique();
$table->string('refresh_token')->unique();
$table->bigInteger('token_expiration');
$table->timestamps();
});
}
And for users it would be like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->boolean('admin')->default(false);
$table->integer('color_scheme')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->engine = "InnoDB";
$table->foreignId('discord_id');
$table->foreign('discord_id')->references('id')->on('discord_o_auths');
});
}

1215 Impossible d'ajouter des contraintes d'index externe

i want to create foreign table and product table keys but it gives me error.
1215 Unable to add external index constraints
(SQL: alter table `category_product` add constraint` category
_product_category_id_foreign` foreign key (`category_id`) references` category` (`id`) on delete cascade)
i don't know where exactly is the error.
products table
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('details')->nullable();
$table->integer('price');
$table->string('description');
$table->timestamps();
});
categories table
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});
category_product table
Schema::create('category_product', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')
->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')
->on('category')->onDelete('cascade');
$table->timestamps();
});

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

Getting error: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint in Laravel 5

I have this four tables but I'm getting the above error in Laravel eloquent. can anyone tell what am I missing here? But when I remove the foreign method the migration works fine.
Schema::create('students', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('first_name');
$table->string('last_name');
$table->string('middle_name');
$table->date('birthdate');
$table->integer('degree_id')->unsigned();
$table->index(['id','first_name', 'last_name']);
$table->timestamps();
$table->foreign('degree_id')
->references('id')
->on('degrees');
});
I included unsigned method but still getting the above error.
Schema::create('degrees', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('description');
$table->string('category_id');
$table->integer('duration');
$table->string('sub_code');
$table->timestamps();
$table->foreign('sub_code')
->references('id')
->on('courses');
});
Here's the other two tables.
Schema::create('instructors', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('first_name');
$table->string('middle_name');
$table->string('last_name');
$table->date('birthdate');
$table->index(['id', 'first_name', 'last_name']);
$table->timestamps();
});
And the last table:
Schema::create('courses', function (Blueprint $table) {
$table->string('id')->unique();
$table->string('description');
$table->integer('no_of_units');
$table->string('room_id');
$table->date('schedule');
$table->integer('instructor_id')->unsigned();
$table->timestamps();
$table->foreign('instructor_id')
->references('id')
->on('instructors');
});
The order of your migration files matters. If you're creating the students table first before the degrees table, your foreign key constraint will fail because the degrees table hasn't been created yet.
To solve this, you can move all your foreign key constraints into a migration create_foreign_key_constraints_migration which should run last.

Resources