I'm on Laravel 5.8 on a XAMPP stack.
Consider these two migrations to create two tables:
post_categories table.
Schema::create('post_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->string('status');
$table->timestamps();
});
posts table.
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->mediumText('description');
$table->integer('views');
$table->integer('post_category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('post_category_id')->references('id')->on('post_categories');
});
When I run php artisan migrate, I'm getting the following error:
General error: 1005 Can't create table testdb.#sql-38d8_102 (errno: 150 "Foreign key constraint is incorrectly formed").
I've tried running both:
php artisan migrate
php artisan migrate:fresh
I also tried changing the post_category_id field to a regular integer, instead of unsigned: no difference.
Also restarted the MySQL server and Apache service, didn't make a difference.
The post_categories migration runs before the posts migration. The posts table gets created, but the foreign key doesn't.
Why is this error being thrown and how do I solve it?
This might be happening because you're trying to create a foreign key with an integer field to a big integer field. In your posts migration, instead of this
$table->integer('post_category_id')->unsigned();
do this:
$table->bigInteger('post_category_id')->unsigned();
Instead of this:
$table->integer('post_category_id')->unsigned();
Try this:
$table->unsignedBigInteger('post_category_id');
I had the same error where I wanted to link two tables, users tables and deposits tables. I tried many options but they didn't work. However, this is what worked for me on create deposits migration:
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Related
This question already has answers here:
How to fix error on Foreign key constraint incorrectly formed in migrating a table in Laravel
(29 answers)
Closed 1 year ago.
I have a database Migration in Laravel 8 that goes like this:
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->string('slug');
$table->text('description');
$table->text('body');
$table->string('imageUrl');
$table->string('tags');
$table->integer('viewCount')->default(0);
$table->integer('commentCount')->default(0);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
But whenever I want to run this, I get this error:
General error: 1005 Can't create table elearning.articles (errno: 150 "Foreign key constraint is incorrectly formed")
I don't what the heck is going wrong here, so if you know how to solve this issue, please let me know...
Instead of using:
$table->integer('user_id')->unsigned();
Use:
$table->unsignedBigInteger();
Laravel uses unsignedBigInteger which is 20 digits and unsignedInteger only takes 11 digits
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
are the engine of the user's table and the articles table the same and it is both InnoDB? MyISAM does not support foreign keys.
if it is, is the articles table will create after the user table? if the answer is yes so :
is both fields are exact in the same type? I think your user id is autoincremented, if it is, then adds unsigned in foreign key :
$table->foreign('user_id')->unsigned()->references('id')->on('users')->onDelete('cascade');
Try this for Laravel 8
$table->id();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->on('users')->references('id')->onDelete('cascade');
My Laravel App is creating all tables in migrations successfully but it's failing to create a foreign keys relationships in the table or even enforce cascade when I delete the primary record.
Here is the migration.
Schema::create('articles', function (Blueprint $table) {
$table->id('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
When I run php artisan migrate it's migrating successfully.
λ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.11 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.1 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.07 seconds)
Migrating: 2020_08_26_122846_create_articles_table
Migrated: 2020_08_26_122846_create_articles_table (0.14 seconds)
But, when I check the database, the relationship is not getting created, just and index for foreign key.
Check the Articles Table image in this link. I have marked the necessary parts
Check the Users Table image here. I have highlighted the primary key.
I have added some factory data relating the user and article and when I delete the user, the articles are being left as orphans.
What could be wrong?
PHP Version: 7.3.21
MySql Version: 5.7.31
MariaDB Version: 10.4.13
Laravel Framework Version: 7.25.0
Thank-you in advance.
The question has been answered in the comment by #ShakilAhmmed here
All I did was go to config folder then database.php and change mysql database engine from null to innoDB
i.e.
From:
//...
'engine' => null,
//...
To:
//...
'engine' => 'InnoDB',
//...
You're using Schema::create for creating the tables.
In the Laravel docs, I see Schema::table when working with foreign keys. Perhaps you should try to split your code:
Schema::create('articles', function (Blueprint $table) {
$table->id('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
});
Schema::table('articles', function (Blueprint $table) {
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
I am trying to forward engineer my new schema onto my db server, but I can't figure out why I am getting this error. I've tried to search for the answer here, but everything I've found has said to either set the db engine to Innodb or to make sure the keys I'm trying to use as a foreign key are primary keys in their own tables.And some guys said that different data types both of these column,but I am make sure that the same of both of two column data types. I have done both of these things, if I'm not mistaken. Any other help you guys could offer?
the users table migration code:
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->unsignedBigInteger('batch_id')->nullable()->default(0);
$table->rememberToken();
$table->unsignedInteger('create_at')->nullable()->default(0);
$table->foreign('batch_id')->references('id')->on('batches')->onUpdate('cascade')->onDelete('cascade');
});
the batches table migration code:
Schema::create('batches', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->string('name',200)->unique();
$table->unsignedInteger('create_at')->nullable()->default(0);
});
I've multiple packages and users can only have one package at a time, not multiple. So, I've created one to one relationship and added a foreign key in my users table.
Here's the relevant users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('role');
$table->unsignedInteger('package_id');
$table->rememberToken();
$table->nullableTimestamps();
$table->foreign('package_id')
->references('id')
->on('packages');
});
}
And here's the packages table:
public function up()
{
Schema::create('packages', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('price');
$table->integer('space');
$table->string('space_type');
$table->string('trial')->nullable();
$table->string('trial_period')->nullable();
$table->string('password_protected_links')->nullable();
$table->nullableTimestamps();
});
}
However, when I ran php artisan migrate:refresh than it appeared the following error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'clouder.#sql-834_1
4' (errno: 150) (SQL: alter table `users` add constraint users_package_id_f
oreign foreign key (`package_id`) references `packages` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'clouder.#sql-834_1
4' (errno: 150)
However, I believe I've created the foreign key correctly. Is there anything else that I've made a mistake?
I've fixed the issue by myself now. The issue I was experiencing is caused by the order of the migration. The create_users_table migration comes with Laravel 5.2 out of the box as such when I've created new migrations create_packages_table the order of the create_users_table migration on the first and it was loading before the create_packages_table. As such when the query trying to create the foreign key it can't find the column on the packages table. So, simply renaming the create_users_table date to ensure it loads after the create_packages_table fixed the issue.
I hope someone may find it helpful in some days.
Due to Laravel migration system, we can create database tables by running the following command lines.
php artisan migrate:make create_users_table
class CreateUserTable extends Migration {
public function up() {
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('name');
$table->timestamps();
});
}
public function down() {
Schema::drop('users');
}
}
php artisan migrate
If I work with relational database and have two tables, A and B. Table A is related to table B by a foreign key. Is it possible to create such database tables with Laravel Migration System? Or do I need to configure the relationship in phpmyadmin manually?
yes its possible to create forgien keys in laravel migration
$table->foreign('fk_id')->references('primary_key')->on('fk_table')->onDelete('cascade');
You can set foreign keys etc using the schema see here.
Example...
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
Also if you are creating tables I would advise using this site to help build your schema, much easier to visualise and work with.