I have a table offer where I stored multiple date range for a product.
------------------table----------------------
offer_id | sdate | edate | price
1 | 5-08-2019 | 10-08-2019 | 200
1 | 15-08-2019 | 20-08-2019 | 200
The problem is when I want to store a new date range for offer_id 1 should not match or between a stored date range.
if I want to store 02-08-2019 to 05-08-2019 should not be saved. either if I want to store 06-08-2019 to 12-08-2019 should not be store because of 06-08-2019 between the first record.
$saveStartDate = Test::where('offer_id',1)->pluck('sdate');
$saveEndDate = Test::where('offer_id',1)->pluck('edate');
$startDate = $request->sdate;
$endeDate = $request->edate;
// validation
foreach($saveStartDate as $saveStartValue){
if($saveStartValue > $startDate ){
foreach($saveEndDate as $saveEndValue){
if($saveEndValue > $saveEndDate){
return "go to save";
}
}
}
}
return "exit";
You could check if the an existing record overlaps with the requested date range:
if (Test::whereBetween('sdate', [$startDate, $endDate])
->orWhereBetween('edate', [$startDate, $endDate])
->exists()) {
echo('Requested date range overlaps with an existing record');
}
You can try to use Carbon
to parse the requested date then check the existing record in DB to determine the two date range if overlap.
$startDate = \Carbon\Carbon::parse($request->sdate);
$endeDate = \Carbon\Carbon::parse($request->edate);
$dataCount = Test::whereBetween('sdate', [$startDate, $endeDate])
->orWhereBetween('edate', [$startDate, $endeDate])->count();
if($dataCount > 0){
return "go to save";
}
I solve my problem but I use more than 1 condition
$data = Test::get();
$i = Test::where(function ($query) use ($startDate, $endDate) {
$query->where(function ($query) use ($startDate, $endDate) {
$query->where('start_date', '>=', $startDate)
->where('end_date', '<', $startDate);
})
->orWhere(function ($query) use ($startDate, $endDate) {
$query->where('start_date', '<', $endDate)
->where('end_date', '>=', $endDate);
});
})->count();
if($i == 0){
$check = Test::where('service_detail_id', $id)
->whereNotBetween('start_date', [$startDate, $endDate])
->where('start_date','>', $startDate)
->where('start_date','>' , $endDate )
->get();
if(count($check) > 0 ){
$i = 0;
}
else{
$i = 1;
}
}
if($i == 0){
foreach($data as $value){
if($value->start_date < $startDate && $value->end_date > $startDate ){
$i =1;
}else{
$i =0;
}
}
}
if($i == 0){
return "go and store";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.