我一直收到此错误未定义的变量:checkInDate ,当我已经定义它时。
public function checkAvailable(Request $request){
$checkInDate = date("Y-m-d", strtotime($request->start_date));
$checkOutDate = date("Y-m-d", strtotime($request->end_date));
$availableRooms = availableRoom::whereHas('reservation',function($query){
$query->where(function($query){
$query->whereDate('reservationDate', '>=', $checkInDate);
$query->whereDate('reservationDate', '<=', $checkOutDate);
})->orWhere(function($query){
$query->whereDate('expiryDate', '>=', $checkInDate);
$query->whereDate('expiryDate', '<=', $checkOutDate);
});
})->get();
return $availableRooms;
}
checkInDate已经具有一个值。我想念什么吗?
答案 0 :(得分:1)
您需要在每个函数中添加一个use(),以便该函数可以访问该变量,否则它只能访问传递给该变量的变量。
public function checkAvailable(Request $request){
$checkInDate = date("Y-m-d", strtotime($request->start_date));
$checkOutDate = date("Y-m-d", strtotime($request->end_date));
$availableRooms = availableRoom::whereHas('reservation',function($query) use ($checkInDate, $checkOutDate) {
$query->where(function($query) use ($checkInDate, $checkOutDate){
$query->whereDate('reservationDate', '>=', $checkInDate);
$query->whereDate('reservationDate', '<=', $checkOutDate);
})->orWhere(function($query) use ($checkInDate, $checkOutDate){
$query->whereDate('expiryDate', '>=', $checkInDate);
$query->whereDate('expiryDate', '<=', $checkOutDate);
});
})->get();
return $availableRooms;
}
答案 1 :(得分:1)
由于您试图在回调中访问变量,因此需要使用do.call(rbind, Map(cbind, index = seq_along(foo), foo))
# index x y
#1 1 a 1
#2 1 b 2
#3 1 c 3
#4 2 d 4
#5 2 e 5
#6 2 f 6
语句将变量传递给回调。
use
由于您还尝试使用public function checkAvailable(Request $request){
$checkInDate = date("Y-m-d", strtotime($request->start_date));
$checkOutDate = date("Y-m-d", strtotime($request->end_date));
$availableRooms = availableRoom::whereHas('reservation',function($query)use($checkInDate, $checkOutDate){
...
});
,因此还需要将其传递给回调,并以逗号分隔。
答案 2 :(得分:0)
替换:
$availableRooms = availableRoom::whereHas('reservation',function($query){
作者:
$availableRooms = availableRoom::whereHas('reservation',function($query) use($checkInDate,$checkOutDate) {