Ad

Cant Add Foreign Key In Laravel

- 1 answer

When I try to migrate I get an error "Foreign key constraint is incorrectly formed", but I cant see why

1st table

    Schema::create('uciteles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('admin');
        $table->string('predmet');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->rememberToken();
        $table->timestamps();

        $table->unsignedBigInteger('user_id');

        $table->foreign('user_id')->references('id')->on('users');
    });

2nd table

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->rememberToken();
        $table->timestamps();

    });
Ad

Answer

i think here first you create uciteles table then users table. so here change that format.first create users table & then uciteles table.

change the time of created table in migration like this 2019_09_27_000000_create_users_table.php change date & month then users table create first & secondly the uciteles table or disble foreign key check & enable it

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::create('uciteles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('admin');
        $table->string('predmet');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->rememberToken();
        $table->timestamps();

        $table->unsignedBigInteger('user_id');

        $table->foreign('user_id')->references('id')->on('users');
    });
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

Ad
source: stackoverflow.com
Ad