我必须采取一个日期范围,并保存到数据库的每个单独的日期到该范围。但日期保存为'0000-00-00'格式,尽管日期在控制器上正确传递。
code my controller:
public function store(Request $request)
{
// dd($request->all());
$validator = Validator::make($request->all(), [
'title' => 'required|max:191',
'start_date' => 'required',
]);
if ($validator->fails()) {
if($request->ajax()){
return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
}else{
return redirect('holidays/create')
->withErrors($validator)
->withInput();
}
}
$startDate = new Carbon($request->start_date);
$endDate = new Carbon($request->end_date);
$all_dates = array();
while ($startDate->lte($endDate)){
$all_dates[] = $startDate->toDateString();
$startDate->addDay();
}
// dd($all_dates);
if(isset($request->start_date)){
foreach($all_dates as $holdate){
$holiday= new Holiday();
$holiday->title = $request->input('title');
$holiday->start_date = $holdate;
$holiday->end_date = $request->input('end_date');
$holiday->company_id = company_id();
// dd($holiday);
$holiday->save();
}
}
//Set Related Data
if(! $request->ajax()){
return redirect('holidays')->with('success', _lang('Saved Sucessfully'));
}else{
return response()->json(['result'=>'success','action'=>'store','message'=>_lang('Saved Sucessfully'),'data'=>$account]);
}
}
表单在我的页
{{csrf_field()}}{{_lang("标题")。"("。_lang("度假")。‘)’}}<div class="col-md-12">
<div class="form-group">
<label class="control-label">{{ _lang('Start Date') }}</label>
<input type="text" class="form-control datepicker" name="start_date" value="{{ old('start_date') }}" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label">{{ _lang('End Date') }}</label>
<input type="text" class="form-control datepicker" name="end_date" value="{{ old('end_date') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="reset" class="btn btn-danger">{{ _lang('Reset') }}</button>
<button type="submit" class="btn btn-primary">{{ _lang('Save') }}</button>
</div>
</div>
</form>
在我的Holiday模式下,我声明了这样一个函数
类Holiday扩展了Model{$table = '节假日';
public function setStartDateAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}
}
因为这个setStartDateAttribute()方法我的start_date得到空值。现在我注释掉了这个方法。