PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

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

 January 08, 2022     laravel, laravel-8, laravel-migrations, mysql, php     No comments   

Issue

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...


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



Answered By - S. Hossain
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing