<?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。我不确定在验证期间究竟如何做到这一点。任何帮助,将不胜感激