SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Posted 1 year ago by irankhosravi

I have a form with the following fields:

public function up()
{
    Schema::create('submit_applications', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('requisition_id')->nullable()->unsigned();
        $table->integer('school_id')->nullable()->unsigned();
        $table->integer('approved')->nullable(true);
        $table->string('application')->nullable(true);
        $table->timestamps();
        $table->foreign('requisition_id')->references('id')->on('requisitions');
        $table->foreign('school_id')->references('id')->on('schools');
    });
}

In my controller I am first saving the record in the submit_applications table like this:

public function store(Request $request)
{
    $form = new SubmitApplication();
    $form->school_id =  1;
    $form->requisition_id = 1;
    $form->approved = 0;
    $form->application = $request->application;
    $form->save();
    return redirect(route('submit-application.create'))->with('success', 'Saved.');
}

The Requisition model is set up like this:

class Requisition extends Model
{
    public function school()
    {
        return $this->belongsTo(SchoolsList::class);
    }

    public function submitApplication()
    {
        return $this->belongsTo(SubmitApplication::class);
    }
}

So, when I try to persist new content record, I get the error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (prj_tvto.submit_applications, CONSTRAINT submit_applications_requisition_id_foreign FOREIGN KEY (requisition_id) REFERENCES requisitions (id)) (SQL: insert into submit_applications (school_id, requisition_id, approved, application, updated_at, created_at) values (1, 1, 0, درخواست مرخصی, 2018-06-20 06:33:33, 2018-06-20 06:33:33))

Please sign in or create an account to participate in this conversation.