Majeed

PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

Posted 2 months ago by Majeed

Hi, Here i'm working on Laravel5.8 i'm using foreign_key constraint in my migrations. but when i going to migrate it's show an error.

PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

** but the same code run properly in laravel5.7 version**

Here is a change between laravel5.8 which is bigIncrements .

Here is my code sample.

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->softDeletes();
            $table->timestamps();
        });
  Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->text('description');
            $table->softDeletes();
            $table->timestamps();
        });
Schema::create('role_user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();

            /** database side relation constraint */
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        });

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.