I am new to web development in Laravel 5.2 and I have this problem. I have a Users and Jobseekers tables and I am trying to create a foreign key in the Jobseekers table that references the Users table using migration but when I run php artisan migrate I get the error
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key cons
traint fails (jobsitelara
.#sql-1a04_7d
, CONSTRAINT jobseekers_user_id_foreign
FOREIGN KEY (user_id
) REFERENCES users
(id
)) (SQL: alter table jobseekers
add constraint jobseekers_user_id_foreign fore
ign key (user_id
) references users
(id
))
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key cons
traint fails (jobsitelara
.#sql-1a04_7d
, CONSTRAINT jobseekers_user_id_foreign
FOREIGN KEY (user_id
) REFERENCES users
(id
))
Here is the migration for create_users_table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
and the migration for create_jobseekers_table
public function up()
{
Schema::create('jobseekers', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->enum('gender',array('male','female'));
$table->date('dateofbirth');
$table->string('occupation', 150);
$table->string('educationlevel', 200);
$table->string('cv', 150);
$table->string('skills', 200);
$table->string('address', 200);
$table->string('phonenumber', 30);
$table->integer('user_id');
$table->timestamps();
});
}
and the migration to create the foreign key is in a separate file that runs after the create tables migrations have been run here is the add_foreignkey_to_jobseekers_table migration
public function up()
{
Schema::table('jobseekers', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
I made sure that the user_id field in the Jobseekers table is also unsigned. I noticed that the tables are referenced as jobsitelara'.'#sql-1a04_8f' in the error messages, I don't understand what's going on. What else is wrong with my code?