Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel – how to redirect Integrity constraint violation: 1451 to failed notifications?

I have a table named merks and it’s id is a foreign key in another table named barangs.
so when I tried to delete a data in table merks but the data have been used in table barangs, it give me this

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (inventorylite.barangs, CONSTRAINT barangs_merk_id_foreign FOREIGN KEY (merk_id) REFERENCES merks (id))

but I want to give user a notifications like,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Cant delete this item because its already used"

and redirect them into index view,

this is my destroy controller

public function destroy($id)
    {
        $delete = Merk::destroy($id);
        if($delete){
            return redirect()->route('merk.index')->with('success', 'Merk barang berhasil dihapus');
        }else{
            return redirect()->route('merk.index')->with('failed', 'Merk barang gagal dihapus');
        }
    }

but it’s not working, is there any solutions for this?
thanks in advance..

>Solution :

Use try and catch for it. Example code is here

public function destroy($id)
{
try {
    $delete = Merk::destroy($id);
}
catch (Exception $ex) {
return redirect()->route('merk.index')->with('failed', 'Merk barang gagal dihapus');
}
return redirect()->route('merk.index')->with('success', 'Merk barang berhasil dihapus');
  
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading