0

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

Pouya
  • 114
  • 1
  • 8
  • 36
  • @rickdenhaan No it does not answer my question because the solution of that question cannot be applied to this one. – Pouya Dec 26 '21 at 10:53
  • Then can you edit your question and explain what solutions you have tried and why they didn't work for your situation? The question I linked has 27 answers with various possible solutions for this issue, from checking to ensure the tables are InnoDB tables to making sure the tables are created in the correct order and the two columns you're linking together are of the same type and properties. – rickdenhaan Dec 26 '21 at 10:57

3 Answers3

2

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

blackbishop
  • 30,945
  • 11
  • 55
  • 76
S. Hossain
  • 71
  • 6
0

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');
behzad m salehi
  • 1,038
  • 9
  • 23
0

Try this for Laravel 8

$table->id();
 $table->unsignedBigInteger('user_id')->unsigned();
 $table->foreign('user_id')->on('users')->references('id')->onDelete('cascade');
Engr Talha
  • 386
  • 2
  • 6