我正在使用" maatwebsite / excel"包导入excel文件并将文件内容插入数据库。现在我想在插入之前验证列,但是我遇到了错误。我的验证将我抛到一个空页面而不是返回上一页并显示错误消息。
这是我的控制者:
public function bulk_upload(Request $request){
$method = $request->isMethod('post');
if($method) {
if ($request->hasFile('file')) {
//dd('true');
Excel::load($request->file('file')->getRealPath(), function ($reader) {
//Do
$i = 2;
foreach ($reader->toArray() as $key => $row) {
$i++;
$name = $row['name'];
$address = $row['address'];
$phone = $row['phone'];
$sex = $row['sex'];
$email = $row['email'];
$next_of_kin_phone_number = $row['next_of_kin_phone_number'];
$dob = $row['date_of_birth'];
//dd($row);
//validate compulsory
if ($name == "" || $address == "" || $phone == "") {
return back()->withErrors("Either patient's name, phone number or address is missing at "."line ".$i);
//dd("error");
}
//sex
if (isset($sex)) {
if (!is_numeric($sex)) {
return back()->withErrors("Wrong format for sex");
}
}
//email
if (isset($email)) {
$count = Patient::where('email', $email)->count();
if ($count > 0) {
return back()->withErrors("Email address is already taken!");
}
}
//phone number
if (isset($phone)) {
if (!is_numeric($phone)) {
return back()->withErrors("Phone number must be numbers!");
} elseif (strlen($phone) != 11) {
return back()->withErrors("Phone number must be 11 digits!");
}
}
//next of kin number
if (isset($next_of_kin_phone_number)) {
if (!is_numeric($next_of_kin_phone_number)) {
return back()->withErrors("Next of Kin Phone number must be numbers!");
} elseif (strlen($next_of_kin_phone_number) != 11) {
return back()->withErrors("Next of Kin Phone number must be 11 digits!");
}
}
//dob
if (isset($dob)) {
if (!preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-[0-9]{4}$/", $dob)) {
return back()->withErrors("Wrong date of birth format!");
}
}
}
dd("validated");
});
}
}
}
查看:
<div class="alert alert-danger">
<ul style="padding-left: 0px;">
@foreach($errors->all() as $error)
<li style="list-style: none">{{ $error }}</li>
@endforeach
</ul>
</div>
<form class="" method="post" action="{{url('patients/bulk-upload')}}" accept-charset="UTF-8" id="users-form" enctype=multipart/form-data>
{{csrf_field()}}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputName1">Select File</label>
<input type="file" name="file" id="exampleInputName1" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="exampleInputName1"><strong>Download Sample file <a href="">here</a> </strong></label>
</div>
</div>
<br>
<button type="submit" class="btn btn-success btn-fw">Submit</button>
</form>
路线:
Route::match(['post','get'], 'patients/bulk-upload', 'PatientController@bulk_upload');