我在视图中设置了两个日期选择器;一个用于开始日期,一个用于结束日期。
请求将传递给控制器索引方法,在该方法中,它与此if
块进行交互。
如果我设置了开始日期,例如1st of April
,我希望:
$start_date == 2017-04-01 00:00:00
$end_date == 2017-04-08 00:00:00
(一周之后)但是当我在阻止后运行dd($start_time.' '.$end_time)
时,它会返回
2017-04-08 00:00:00 2017-04-08 00:00:00
// If start or end date is not passed, set the bookings to view the upcoming week
if (isset($request->start_date) && isset($request->end_date))
{
$start_date = Carbon::parse($request->start_date);
$end_date = Carbon::parse($request->end_date);
if ($start_date->diffInDays($end_date, false) < 1 )
{
return redirect()->route('bookings.index')->with('errors', 'Please choose an end date <strong>after</strong> start date!');
}
}
else if (isset($request->start_date))
{
$start_date = Carbon::parse($request->start_date);
$end_date = $start_date->addWeek();
}
else if (isset($request->end_date))
{
$end_date = Carbon::parse($request->end_date);
$start_date = ($end_date->subWeek());
}
else
{
$start_date = Carbon::now();
$end_date = Carbon::now()->addweek();
}
这可能会发生什么?
答案 0 :(得分:1)
代码中出现问题是因为 Carbon对象是可变的。
这基本上意味着当您$end_date = $start_date->addWeek();
时,start_date
和end_date
都是相同的对象。
所以你可以clone
start_date
到end_date
,然后再调用方法。
解决方案应为
// If start or end date is not passed, set the bookings to view the upcoming week
if (isset($request->start_date) && isset($request->end_date))
{
$start_date = Carbon::parse($request->start_date);
$end_date = Carbon::parse($request->end_date);
if ($start_date->diffInDays($end_date, false) < 1 )
{
return redirect()->route('bookings.index')->with('errors', 'Please choose an end date <strong>after</strong> start date!');
}
}
else if (isset($request->start_date))
{
$start_date = Carbon::parse($request->start_date);
$end_date = clone $start_date;
$end_date = $end_date->addWeek();
}
else if (isset($request->end_date))
{
$end_date = Carbon::parse($request->end_date);
$start_date= clone $end_date;
$start_date= $start_date->subWeek();
}
else
{
$start_date = Carbon::now();
$end_date = Carbon::now()->addweek();
}