php - 如何考虑laravel excel上传中唯一规则中的现有ID?
问题描述
<?php
namespace App\Imports;
use App\Models\Customer;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
class CustomerImport implements ToCollection, WithHeadingRow, WithValidation
{
public $timestamps = false;
public function collection(Collection $rows)
{
foreach ($rows as $row) {
Customer::create([
'name' => $row['name'],
]);
}
}
public function rules(): array
{
return [
'name' => [
'required',
'max:50',
'unique:customers,name',
],
];
}
}
我的控制器代码如下:
public function uploadFile(Request $request)
{
$request->validate(
['file' => ['required', 'file', 'mimes:txt,csv']],
['file.required' => 'Please upload the file']
);
try {
Excel::import(new CustomerImport(), $request->file('file'));
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
return redirect()
->route('customers.upload')
->withErrors($failures);
}
return redirect()
->route('customers.index')
->with('success', __('customers.message_uploaded'));
}
我创建了一个客户,然后想更改其名称。我该怎么做?我不能上传相同的名字。因为它不会是唯一的。所以我在尝试唯一性时需要考虑id。我不确定在验证期间究竟如何做到这一点。任何帮助,将不胜感激
解决方案
从外观上看,您没有以任何方式存储选择,因此在页面刷新后,服务器无法知道呈现通过 Javascript 操作完成的结果。
将更改存储在 cookie、会话或本地存储中,然后在渲染时检索数据。
推荐阅读
- c - 尝试锁定 EOWNERDEAD 状态互斥锁
- google-apps-script - 我应该如何在 Google 表格中显示 ~1600 个迷你图?
- swift - Swift - 声明没有数据类型的空集合?
- python - 检查字典值列表中的值,python
- atom-editor - 如何将自定义语法加载到 atom 中?
- python - “MyTestClass”的实例没有“assertEqual”成员pylint(无成员)VScode
- python - Pandas:如何按数据框分组并将行转换为列并合并行
- express - 如何正确使用 express 静态文件构建 Nuxt?
- vim - 在 vim 中突出显示 gnuplot
- cmake - 如何将自定义路径中的框架链接到我的可执行文件?