0
votes

I have two tables like User and Roles . i want to added foreign Roles_id on Table Users .

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('NIK',16);
        $table->string('nama');
        $table->string('email')->unique();
        $table->string('username');
        $table->string('password');
        $table->unsignedBigInteger('roles_id')->default(1);

        $table->timestamps();
        $table->softDeletes();

        $table->foreign('roles_id')->references('id')->on('roles');
    });
}

and my roles table

 public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('roles');
        $table->timestamps();
    });
}

iam not catching the miss code , i using unsignedBigInteger , ann still error . i am using -> nullable . but didnt work . can somone find this error ?

edit . this error :

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_roles_id_foreign foreign key (roles_id) references roles (id))

1
Does the roles migration run before the users table migration?Shree Sthapit
i create the users tables first. now i have 2 table .users and roles . i want to make this foreign . its wrong step ?Adhik Mulat
There must be roles table already created if you want to create role_id as foreign in the users table. What you can do is change the migration file timestamp of role ahead of the users migration file timestamp.Shree Sthapit
ok look my step . i create users table (without FK on roles) , now i create roles table .(i have 2 table now without FK) .now i added foreign like on thread . i run php artisan migrate . and showing "Nothing to Migrate"Adhik Mulat
if i run migrate:fresh its error like on this threadAdhik Mulat

1 Answers

1
votes

First, create the roles table:

 public function up(){
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('roles');
        $table->timestamps();
    });
}

Then create a users table:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('NIK',16);
        $table->string('nama');
        $table->string('email')->unique();
        $table->string('username');
        $table->string('password');

        $table->unsignedBigInteger('roles_id')->nullable();
        $table->foreign('roles_id')->references('id')->on('roles');

        $table->timestamps();
        $table->softDeletes();
    });
}

For drop the foreign key:

Schema::table('users', function (Blueprint $table) {
    $table->dropForeign('users_roles_id_foreign');
    $table->dropColumn('roles_id');
});