Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mhmmdva's avatar

(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `users` add constraint `users_role_id_foreign` foreign key (`role_id`) references `roles` (`id`))

so i want create 3 roles on the table, but always error foreign key constraint

table users

<?php

use App\Models\Role;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id(); // primary key

            // main data
            $table->bigInteger('nidn')->unique(); // bersifat unik
            $table->string('fullname');            
            $table->string('email')->unique();
            $table->string('password');

            // detail
            $table->enum('faculty', ['FTIK', 'FEIS']);
            $table->string('major')->nullable();
            $table->string('telp')->unique()->nullable();
            $table->date('birthdate')->nullable();
            $table->enum('gender', ['Pria', 'Wanita']);
            $table->text('address')->nullable();
            $table->text('image')->nullable();

            // identifier       
            $table->unsignedBigInteger('role_id');
            $table->foreign('role_id')->references('id')->on('roles');
            // $table->boolean('is_active')->default(true);
            // $table->dateTime('last_login')->nullable();

            // system
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();;
            
            
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

table roles

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

user model

public function role(){
        return $this->belongsTo(Faculty::class, 'role_id', 'id');
    }

role model

 public function user(){
        return $this->hasMany(User::class);
    }
0 likes
17 replies
mhmmdva's avatar

i used laravel 8 and PHP version 7.4

but why always error. if I use PHP version 8 it doesn't error

i don't know why

mhmmdva's avatar

@shariff

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}
tykus's avatar

Probably because the roles table does not exist before you attempt to migrate the users table. If possible, change the timestamp in the filename for the roles table to pre-date the users table migration to ensure there is a roles table to be referenced. Otherwise, make a separate migration to add the foreign key and constraint.

tykus's avatar

@mhmmdva your users table migration is running before there is a roles table to be referenced. You need to ensure that the roles table is migrated first!

mhmmdva's avatar

@Tray2 the error remains the same

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id(); // primary key

            // main data
            $table->bigInteger('nidn')->unique(); // bersifat unik
            $table->string('fullname');            
            $table->string('email')->unique();
            $table->string('password');

            // detail
            $table->enum('faculty', ['FTIK', 'FEIS']);
            $table->string('major')->nullable();
            $table->string('telp')->unique()->nullable();
            $table->date('birthdate')->nullable();
            $table->enum('gender', ['Pria', 'Wanita']);
            $table->text('address')->nullable();
            $table->text('image')->nullable();

            // identifier       
            $table->unsignedInteger('role_id');
           
            // system
            $table->timestamp('email_verified_at')->nullable();
            $table->timestamps();;
            $table->foreign('role_id')->references('id')->on('roles');            
            $table->rememberToken();
            
            
        });
    }
tykus's avatar
tykus
Best Answer
Level 104

@mhmmdva please change the filename for the roles table migration. The users table migration is (probably) 2014_10_12_000000_create_users_table; whereas the roles table is some date after 2014_10_12 - do you understand now?

Tray2's avatar

@mhmmdva The order the migrations is run matters, you can't run one migration that references a table unless the migration that is creating that table is run first. In short the table must exist in the database before you create the constraint.

1 like
mhmmdva's avatar

@tykus I just found out if the timestamp has an effect. It's resolved thanks

tykus's avatar

@mhmmdva yes...

If possible, change the timestamp in the filename for the roles table to pre-date the users table migration to ensure there is a roles table to be referenced

tykus's avatar

@Tray2 yes, already covered that earlier

Otherwise, make a separate migration to add the foreign key and constraint.

1 like
mhmmdva's avatar

@tykus @Tray2 okay maybe next time i want try to it. thank you for the advice which is very useful for me

Please or to participate in this conversation.