I am importing new users from an excel file with Laravel-Excel.
I would like to know if it's possible to throw an error if there is two users with a same email in the import file, while keeping the implementation of the current interfaces.
My UsersImport class is declared like so:
class UsersImport implements ToModel,
WithHeadingRow,
WithValidation,
WithBatchInserts,
WithChunkReading
{
private $user;
private $company;
public function __construct($user, $company)
{
$this->user = $user;
$this->company = $company;
}
public function model(array $row)
{
if(!isset($this->company)) return;
if ($this->user->contains('email', $row['email'])) {
$this->throwNotification($row['email']." est déjà utilisé.");
return;
}
Mail::to($row['email'])->send(new NewUser($this->company->name));
$employee = new \App\Models\User($row + [
'company_id' => $this->company->id
]);
return $employee;
}
public function rules(): array
{
return [
'firstname' => 'required|string',
'lastname' => 'required|string',
'*.email' => ['required', 'email', 'unique|users:email'],
'phone' => 'nullable|max:15',
];
}
public function batchSize(): int
{
return 250;
}
public function chunkSize(): int
{
return 250;
}
}
distinctrule that looks for duplicates within an array? laravel.com/docs/8.x/validation#rule-distinctdistinctrule did the trick. It avoids to start a DB transaction which would fail.