首页 > 解决方案 > 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');

标签: phplaravel

解决方案


您的检查也将起作用,就好像它返回的查询没有保留,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

推荐阅读