Q:

How to foreign key in Laravel 5.3

I use Laravel 5.3 and MySQL
I will to make foreign key on Forums and references on user id
Migration in Users
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 60)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

Migration in Forums
{
    Schema::create('forums', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('thread');
        $table->text('deskripsi');
        $table->timestamps();
    });

    Schema::table('forums', function(Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users');
    });
}

But I get found error 
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dbkelas`.`forums`, CONSTRAINT `forums_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: insert into `forums` (`thread`, `deskripsi`, `updated_at`, `created_at`) values (Matematika Diskrit, Bagaimana ya, 2017-01-14 15:10:18, 2017-01-14 15:10:18))

Do you have any solution?

A:

I think your migration code need to update like:
Schema::create('forums', function(Blueprint $table) {
       $table->increments('id');
       $table->integer('user_id')->unsigned();
       $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
       $table->string('thread');
       $table->text('deskripsi');
       $table->timestamps();
   });

Hope this work for you!

