1
votes

I am new to laravel when adding a new column to the existing table I am getting the above error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (schoolmanagement.#sql-314_2c, CONSTRAINT students_parentsid_foreign FOREIGN KEY (parentsid) REFERENCES parent_names (id) ON DELETE CASCADE) (SQL: alter table students add constraint students_parentsid_foreign foreign key (parentsid) references parent_names (id) on delete cascade)

at

    public function up(){
        Schema::table('students', function (Blueprint $table)
        {
            $table->unsignedBigInteger('parentsid')->after('id');
            $table->foreign('parentsid')->references('id')->on('parent_names')->onDelete('cascade');
        });
    }


    public function down()
    {
        Schema::table('students', function (Blueprint $table) {
            //
        });
    }

just need to insert a column for the existing table with foreign key

1

1 Answers

1
votes

That is because you're trying to create a new column with a foreign key constraint but without setting a default value. So you either set it to be nullable or set a default value (which must be an existed ID in your parent_names table)

$table->unsignedBigInteger('parentsid')->default(1);