SQLSTATE [23000]: Integrity constraint violation: 1452 Unable to add or update child row: foreign key constraint fails
I know this is a common problem, but I don’t know what is wrong here. As you can see it //return $user
is and it shows the valid id. Also checked what's in the database.
$user = new User;
$user->first_name = $data['first_name'];
$user->last_name = $data['last_name'];
$user->email = $data['email'];
$user->phone_no = $data['phone_no'];
$user->created_from = 'Web App';
$user->save();
// return $user;
Session::put('user_id',$user->id);
// return $user->id;
$address = new Address;
$address->user_id = $user->id;
$address->first_name = $data['receiver_first_name'];
$address->last_name = $data['receiver_last_name'];
$address->email = $data['receiver_email'];
$address->address_line_1 = $data['receiver_address_line_1'];
$address->address_line_2 = $data['receiver_address_line_2'];
$address->landmark = $data['receiver_landmark'];
$address->pincode = $data['receiver_pincode'];
$address->phone_no = $data['receiver_phone_no'];
$address->created_from = 'Web App';
$address->save();
Here is the migration: This is the user migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function($table){
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('phone_no', 20)->nullable();
$table->string('password')->nullable();
$table->string('remember_token', 100);
$table->date('date_of_birth')->nullable();
$table->string('created_from');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Addresses
public function up()
{
Schema::create('addresses', function($table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('address_line_1');
$table->string('address_line_2')->nullable();
$table->string('landmark')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('phone_no', 13);
$table->integer('pincode');
$table->string('created_from');
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users');
});
}
Here is a screenshot of the error if it helps.
+3
source to share
2 answers
According to the error message, your error is caused by entering a value in adresses.user_id (FK to src.id) that is not in src.id.
In the example you are trying to insert 29 into adresses.user_id, check if it returns SELECT id FROM src WHERE id=29
any result. If not, there is your problem.
0
source to share