0

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;
    }
}
3
  • 1
    Did you try with the distinct rule that looks for duplicates within an array? laravel.com/docs/8.x/validation#rule-distinct Commented Oct 19, 2021 at 16:55
  • Your user model should already have a unique constraint on email, which means the second attempt to insert one should already be failing. Is that not sufficient? Commented Oct 19, 2021 at 17:05
  • The distinct rule did the trick. It avoids to start a DB transaction which would fail. Commented Oct 22, 2021 at 14:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.