laravel查询重复的数据,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');

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值