laravel防止重复记录 [英] laravel preventing duplicate record
本文介绍了laravel防止重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何正确检查数据库中是否已存在数据并将消息返回到视图中
How to properly check if a data already exist in DB and return message into view
$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
.因此,您也可以尝试以下方法:
Your check will work as well, as if there is no reservation for your query it returns null
which means your else
block will execute. But there is a better method on the query builder called exists
. So you can try this as well:
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
这篇关于laravel防止重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文