$wordsFromFile = array_map(function($data) { return str_getcsv($data,";");}, file($request->file('text_file')) );
// All words from the database
$myWords = Word::all();
$dbWords = [];
foreach ($myWords as $myWord) {
$dbWords[] = $myWord->word;
}
$wordsResult= [];
foreach($wordsFromFile as $key => $data)
{
if($key == 0) {continue;}
$word = isset($data[0]) ? mb_strtolower($data[0]) : "empty_field";
$translation = isset($data[1]) ? $data[1] : "empty_field";
$state = isset($data[2]) ? $data[2] : 0;
//$wordInDatabase = $myWords->where('word', $word)->first();
if(!in_array($word, $dbWords))
{
$wordsResult[] = [
'word' => mb_strtolower($word),
'translation' => mb_strtolower($translation),
'state' => $state,
];
}
}
Word::insert($wordsResult);
Find more questions by tags PHP
Normally INSERT stops and rolls back when it encounters an error.
By using the keyword IGNORE all errors are converted to warnings, which will not stop inserts of additional rows.
Until MariaDB 5.5.28
MySQL and MariaDB 5.5.28 before didn't give warnings for duplicate key errors when using IGNORE. You can get the old behaviour if you set OLD_MODE to NO_DUP_KEY_WARNINGS_WITH_IGNORE
not? - Jackeline_Zboncak commented on April 19th 20 at 12:42
In General , I would try to use it or INSERT...ON DUPLICATE KEY UPDATE. . Ie not to do the check in code, and blame everything on the suffering of MYSQL . - Jackeline_Zboncak commented on April 19th 20 at 12:48