So, is your database table empty, or does the [email protected] email address exist there already?
Duplicate entry for key 'users_email_unique'
Dear,
I'm trying to import a CSV of users. However when i run the import I get the error shown below. There is only one user which is myself and the mailadress is not a duplicate or anything like that. Is there anyone who could point me in the right direction please ?
Error: Import failed: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users_email_unique'
CSV file: Voornaam,Achternaam,Email,Compagnie,Post,Function Some,User,[email protected],1,PN,Coolguy
UsersImport.php:
namespace App\Imports;
use App\Models\User; use Illuminate\Support\Facades\Hash; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithBatchInserts; use Maatwebsite\Excel\Concerns\WithChunkReading; use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UsersImport implements ToModel, WithHeadingRow, WithBatchInserts, WithChunkReading {
public function model(array $row)
{
// Zoek een bestaande gebruiker op e-mail
$user = User::where('email', $row['email'])->first();
if ($user) {
// Als de gebruiker bestaat, update de naam
$user->update([
'name' => $row['voornaam'] . ' ' . $row['achternaam'],
]);
} else {
// Als de gebruiker niet bestaat, maak een nieuwe aan
$user = User::create([
'name' => $row['voornaam'] . ' ' . $row['achternaam'],
'email' => $row['email'],
'password' => Hash::make('defaultpassword'),
]);
}
\Log::info('Importing user:', [
'email' => $row['email'],
'exists' => $user ? true : false,
'name' => $row['voornaam'] . ' ' . $row['achternaam']
]);
return $user;
}
public function batchSize(): int
{
return 100; // Batches van 100 records
}
public function chunkSize(): int
{
return 100;
}
}
You've updated the question since my previous reply; I see now you are using the toModel method incorrectly, it should not be creating a Model instance, per docs:
When using
ToModelyou should never save the model yourself, as that will break the batch insert functionality. If you need this, consider using OnEachRow.
In fact, you should probably consider the Upserting Models instead!
Please or to participate in this conversation.
