I need to validate that a booking doesn’t overlap in date and time with an existing booking and return and error if a booking is overlapping an existing booking.
This is the code I have right now but it isn’t working, and when I make another booking that overlaps an existing booking, it is still passing through and not returning an error.
CREATE TABLE IF NOT EXISTS books ( id integer not null primary key autoincrement created_at datetime, updated_at datetime, carid integer, sdate date not null, edate date not null, stime time not null, etime time not null, userid integer, foreign key("carid") references "cars"("id") on delete cascade, foreign key("userid") references "users"("id") on delete cascade ); $temp=DB::table('books')->where('sdate','>=',$sdate)->where('edate', '<=',$edate)->where('stime', '>=',$stime) ->where('etime','<=',$etime)->get(); if($temp) { $errorMsg="This overlaps with an existing booking, please choose another time."; $code='1'; echo '<script type="text/javascript">alert("'.$errorMsg.'");</script>'; } else { //ok }
Advertisement
Answer
try
$temp=DB::table('books') ->where(function($query)use($sdate,$edate){ $query->whereBetween('sdate', [$sdate,$edate]) ->orWhereBetween('edate', [$sdate,$edate]); })->where('stime','>=',$stime)->orWhere('etime','<=',$etime)->count(); if($temp > 0){ .... }else{ .... }