Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

General error: 1005 Can't create table (errno: 150 "Foreign key constraint is incorrectly formed")

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t what the heck is going wrong here, so if you know how to solve this issue, please let me know…

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading