需求: 导入如下excel表单
先看官方文档
Row Validation
我的想法是,把业务都在model里处理,但有可能是导入的数据检测没问题,但对于业务来说,某项数据会有问题,比如一系列查询后该行数据已存在,需要统一返回到$import->failures()接收,找了官方文档里没有提到这事,所以便自行研究。。
app\Http\controllers下
// 导入附件,获取附件的绝对路径
$fileName = '绝对路径xxx';
$import = new SalarySheetImport(); // php artisan make:import SalarySheetImport
$import->import($fileName); // 绝对路径文件
pp($import->failures(), 'y');
app\Imports\SalarySheetImport.php
class SalarySheetImport implements ToModel, WithStartRow, WithValidation, SkipsOnFailure, WithCalculatedFormulas
{
public function model(array $row)
{
$currentRowNumber = $this->getRowNumber();
$month = $row[0];
$salaryBegin = $row[1];
$salaryEnd = $row[2];
$realName = $row[3];
// 模拟一个错误信息
if ($realName == '小陈') {
$failures = [];
// 构造新的错误
$failures[] = new Failure(
$currentRowNumber, // 行号
3, // 列号
['错误了没啊'], // 错误信息
$row ?? [], // 源数据
);
// new一个RowSkippedException让failures()接收
if ($this instanceof SkipsOnFailure) {
$this->onFailure(...$failures);
new RowSkippedException(...$failures);
}
}
$idcard = $row[4];
}
/**
* 规则
* Author: Wherein
* DateTime: 2022-03-16 17:51
* @return array
*/
public function rules(): array
{
return [
'0' => [
'required'
],
'1' => [
'required',
],
'2' => [
'required',
],
'3' => [
'required'
],
'4' => [
'required',
'idcard'
],
];
}
/**
* 自定义规则错误(跟laravel自动验证的messages一样)
* Author: Wherein
* DateTime: 2022-03-16 17:51
* @return array
*/
public function customValidationMessages()
{
return [
'0.required' => '所属期间必须',
'0.date_format' => '所属期间格式有误',
'1.required' => '计薪范围开始必须',
// '1.date_format' => '计薪范围开始格式有误',
'2.required' => '计薪范围结束必须',
// '2.date_format' => '计薪范围结束格式有误',
'4.idcard' => '身份证格式有误',
];
}
}
先看WithValidation下获取的错误$import->failures()
再来看看模拟自定义错误+WithValidation后的打印: