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
, CONSTRAINTbarangs_merk_id_foreign
FOREIGN KEY (merk_id
) REFERENCESmerks
(id
))
but I want to give user a notifications like,
"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..
CodePudding user response:
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');
}