laravel防止重复记录

时间:2019-05-03 13:57:26

标签: 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');

1 个答案:

答案 0 :(得分:3)

您的检查也将正常工作,就像查询没有保留一样,它返回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