我有一个名为 merks 的表,它的 id 是另一个名为 barangs 的表中的外键。所以当我试图删除表 merks 中的数据但数据已在表 barangs 中使用时,它给了我这个
SQLSTATE [23000]:完整性约束违规:1451 无法删除或更新父行:外键约束失败(
inventorylite
.barangs
, CONSTRAINTbarangs_merk_id_foreign
FOREIGN KEY (merk_id
) REFERENCESmerks
(id
))
但我想给用户一个通知,比如,
“无法删除此项目,因为它已被使用”
并将它们重定向到索引视图,
这是我的销毁控制器
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');
}
}
但它不起作用,有什么解决方案吗?提前致谢..
使用 try and catch 。示例代码在这里
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');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句