我创建了一个表单,用户可以在其中创建一个事件,该表单包含一个日期/时间字段。输入类型允许用户从日历下拉列表中进行选择。
用户必须在表单中选择开始日期和结束日期。
例如,如果用户将开始日期设置为2020年4月1日,并且我希望结束日期在2020年4日1日自动打开,因为结束日期显然会晚于开始日期。有什么好方法可以做到这一点吗?
还假设我需要在我的控制中添加某种单独的验证,以便结束日期总是晚于开始日期。。?
addEvent.blade.php
<div class="form-group">
<div class="form-group">
{!! Form::label('start_date', 'Start Date:') !!}
<div class="">
{!! Form::date('start_date', null, ['class' => 'form-control']) !!}
{!! $errors->first('start_date', '<p class="alert alert-danger">:message</p>') !!}
</div>
</div>
</div>
<div class="form-group">
<div class="form-group">
{!! Form::label('end_date', 'End Date:') !!}
<div class="">
{!! Form::date('end_date', null, ['class' => 'form-control']) !!}
{!! $errors->first('end_date', '<p class="alert alert-danger">:message</p>') !!}
</div>
</div>
</div>
添加事件控制器
public function addEvent(Request $request)
{
$this->validate($request, [
'event_name' => 'required',
'start_date' => 'required',
'end_date' => 'required',
'time' => 'required',
'trip_id' => 'required',
'address' => 'required',
]);
$start_date = Carbon::parse($request['start_date'])->format('Y-m-d');
$end_date = Carbon::parse($request['end_date'])->format('Y-m-d');
$tripCheck = Trip::where('id', $request['trip_id'])
->whereDate('startdate', '<=', $start_date)
->whereDate('enddate', '>=', $start_date)
->whereDate('startdate', '<=', $end_date)
->whereDate('enddate', '>=', $end_date)
->first();
if ($tripCheck) {
$events = new Events;
$trips = Trip::all();
$categories = Categories::pluck('category','id');
$events->category_id = $request['category_id'];
$events->colour = $request['colour'];
$events->event_name = $request['event_name'];
$events->start_date = $request['start_date'];
$events->end_date = $request['end_date'];
$events->time = $request['time'];
$events->address = $request['address'];
$events->notes = $request['notes'];
$events->trip_id = $request['trip_id'];
$events->save();
//return redirect('trips')->with('success', 'The new event has been added to your trip')->with('trips', $trips)->withCategories($categories);
return redirect('trips/'.$request->input('trip_id').'/edit')->with('success', 'The new event has been added to your trip')->with('trips', $trips)->withCategories($categories);
} else
{
return redirect('trips')->withErrors(['The dates you added are not within Trip start and end date.']);
}
}
您可以使用after
或after_or_equal
验证规则:
'start_date' => 'required|date',
'end_date' => 'required|date|after:start_date',
您也可以使用date_format
验证规则来匹配给定的格式:
'start_date' => 'required|date_format:m/d/Y',
'end_date' => 'required|date_format:m/d/Y|after:start_date',