alban
alban

Reputation: 71

Laravel SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row

I want to delete a faculty but I have this error

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (trouverm_m_ecole.etablissement_filieres, CONSTRAINT etablissement_filieres_id_filieres_foreign FOREIGN KEY (id_filieres) REFERENCES filieres (id)) (SQL: delete from filieres where id = 1)

My migration

Schema::create('etablissement_filieres', function (Blueprint $table) {
    $table->id();
    $table->bigInteger('id_etablissements')->unsigned();
    $table->foreign('id_etablissements')->references('id')->on('etablissements');
    $table->bigInteger('id_filieres')->unsigned();
    $table->foreign('id_filieres')->references('id')->on('filieres');
    $table->string('prise_en_charge');
    $table->string('prix');
    $table->string('prix_affecte')->nullable();
    $table->timestamps();
});

my controller

public function destroy($id)
{
    Filiere::destroy($id);

    return redirect('/tableau-de-bord/admin/dashboard/sindhost/toutes-les-filieres');
}

Any ideas ?

Upvotes: 2

Views: 4698

Answers (1)

Chandana
Chandana

Reputation: 199

The problem is, there is a etablissement_filieres record referencing a record of filieres. Unless you have specified what to do when deleting a record refered by another record as a foreign key, it does not allow you to delete the foreign key record. Ideal way to handle this situation is to specify what to do when deleting a foreign key record. Check the Foreign Key Constraints of Laravel documentation to see the available options. Look at the section where it shows how to define the actions such as,

->onUpdate('cascade') ->onDelete('cascade');

Upvotes: 4

Related Questions