php - laravel 防止重复记录
问题描述
如何正确检查数据库中是否已存在数据并将消息返回到视图中
$check = PropertyReservation::where('res_id', Auth::user()->res_id)->where('property_no',$reservation->property_no)->first();
if($check){
return redirect('/reservations')->with('success','You have an existing reservation for this item ' );
}
else{
$reservation->reservation_name = $resident->resident_fname;
$reservation->reservation_type = $request->input('reservation_type');
$reservation->reservation_quantity = $request->input('reservation_quantity');
$reservation->save();
}
return redirect('/reservations');
解决方案
您的检查也将起作用,就好像它返回的查询没有保留,null
这意味着您的else
块将执行。但是查询生成器上有一个更好的方法,称为exists
. 所以你也可以试试这个:
if(PropertyReservation::where('res_id', Auth::user()->res_id)->where('property_no',$reservation->property_no)->exists();
{
// redirect back
}
// no need for else block as this will execute if the condition above is false
// save the reservation
推荐阅读
- sql - 如何在 Where 子句中做 IF 条件
- oracle - 如何在 Oracle Data Pump 中转义特殊字符
- python - Windows 10 上的 Python UDP 广播地址异常
- android - 使用 firebase 的应用程序崩溃
- python - 如何修改计算的查询集值?(反转多对一关系)
- jmeter - 在预处理器中添加具有 int 值的 json 时的 Jmeter 包装器类
- java - 通过数组搜索以匹配用户输入(java)
- mysql - 在 MySQL 表上创建外键需要永远复制到 tmp 表
- reactjs - React JS window.requestAnimationFrame(更新)
- r - R Shiny / shinyapps.io - Worker 和 Instance 设置以最大限度地提高性能