laravel

Laravel 开发记录

导入Excel 生成PDF

1
2
3
4
5
6
7
8
9
10
11
# 导入Excel
composer require maatwebsite/excel
# Laravel注册服务
# - config/app.php
Maatwebsite\Excel\ExcelServiceProvider::class,
# - 注册到 aliases 数组
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
# - 生成 Laravel Excel 的配置文件
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
# - 创建导入文件
php artisan make:import 文件名称

导入文件说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 导入类
# class ExcelImport implements ToCollection, WithValidation,WithStartRow
# WithValidation - 验证字段 - 需实现rules方法,返回数组
# **验证规则 字段按列数读取,需加单引号**
[
'0' => 'required',
'1' => 'required',
'2' => 'required|id_verify' // 核心规则
];
# 身份证验证 id_verify
composer require "chendujin/id-verify"
# WithStartRow - 设置开始行数 - 需实现startRow方法,返回int

# 控制器
try {
Excel::import(new ExcelImport(), $request->file('file'));
} catch (ValidationException $e) {
$failures = $e->failures();
$errors = collect($failures)->mapWithKeys(function ($failure) {
return [$failure->row() => $failure->errors()];
})->all();
return response()->json([
'message' => '导入失败:检测到身份证号错误,请检查 Excel 文件。',
'errors' => $errors
], 422);
}

生成PDF说明

1
2
3
composer require tecnickcom/tcpdf

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);