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