如何解决如何在 Laravel Maatwebsites 导入中显示成功和失败的数据
在使用 Maatwebsites-3.1 的 Laravel-5.8 中,我尝试通过 MS Excel 将员工休假更新到 MySQL 数据库中。
控制器
public function import(Request $request){
$request->validate([
'file' => 'required|max:10000|mimes:xlsx,xls',]);
$path1 = $request->file('file')->store('temp');
$path=storage_path('app').'/'.$path1;
try{
Excel::import(new LeavesImport,$path);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
Log::error($e);
$errormessage = "";
foreach ($failures as $failure) {
$errormess = "";
foreach($failure->errors() as $error)
{
$errormess = $errormess.$error;
}
$errormessage = $errormessage.",\n At Row ".$failure->row().",".$errormess."<br>";
}
Session::flash('error',$errormessage);
return back();
}catch (\Illuminate\Database\QueryException $e)
{
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
Log::error($e);
DB::rollback();
Session::flash('error','You have a duplicate entry problem!');
}
return back();
}
Session::flash('success','Leave Records Imported Successfully');
return redirect()->back;
}
下面是从MS Excel Sheet导入数据的代码 导入
class FirstLeaveSheetImport implements ToModel,WithHeadingRow,WithBatchInserts,WithValidation
{
protected $staffid,$leavetype,$commencementdate,$resumptiondate;
private $errors = []; // array to accumulate errors
use Importable;
return new HrLeaveRequest([
'employee_id' => $this->getStaffId(),'leave_type_id' => $this->getLeaveType(),'commencement_date' => $this->transformDate($row['commencement_date']),'resumption_date' => $this->transformDate($row['resumption_date']),'no_of_days' => $row['leave_days'],]);
}
public function getStaffId(){
if(!empty($this->staffid)){
return HrEmployee::where('employee_code',$this->staffid)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
public function getLeaveType(){
if(!empty($this->leavetype) || !$this->leavetype){
return HrLeaveType::where('leave_type_name',$this->leavetype)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
// this function returns all validation errors after import:
public function getErrors()
{
return $this->errors;
}
public function transformDate($value,$format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format,$value);
}
}
public function batchSize(): int
{
return 200;
}
public function headingRow(): int
{
return 1;
}
}
我想显示:
-
列表成功上传
-
上传失败列表
我如何实现这一目标?
谢谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。