I'm working with Laravel 5.8 and LaravelExcel for importing an Excel file that holds a column named "National Code" and this code must be unique in the Database.
So if a user entered repeated National Codes in his Excel file, a message has to appear and show repeated National Codes to him.
So I coded this at the Import Class:
$query=DB::table('olympiad_1400');
$repeated = [];
foreach($formatArray as $arr){
if(!$query->where('mys_ncode',$arr['nationalCode'])->exists()){
$query->insert([
'mys_object_id' => $objectId,
'mys_object_type_id' => $objectTypeId,
'mys_olp_id' => 4,
'mys_name' => $arr['name'],
'mys_fname' => $arr['family'],
'mys_ncode' => $arr['nationalCode'],
'mys_paid_price' => $arr['price'],
'mys_creator_id' => auth()->user()->usr_id,
]);
}else{
array_push($repeated, $arr['nationalCode']);
}
}
if(!empty($repeated)){
Session::flash('repeated',$repeated);
}
Now if I test this via uploading an Excel file that contains repeated National Codes which already exists in the DB, it shows the first element in the session $repeated
(and ignores inserting it) but surprisingly inserts all the others (however, the are all duplicated).
So how can I fix this and ignore inserting repeated National Codes into the Database?
CodePudding user response:
Try this:
$repeated = [];
foreach($formatArray as $arr){
$query=DB::table('olympiad_1400');
if(!$query->where('mys_ncode',$arr['nationalCode'])->exists()){
$query->insert([
'mys_object_id' => $objectId,
'mys_object_type_id' => $objectTypeId,
'mys_olp_id' => 4,
'mys_name' => $arr['name'],
'mys_fname' => $arr['family'],
'mys_ncode' => $arr['nationalCode'],
'mys_paid_price' => $arr['price'],
'mys_creator_id' => auth()->user()->usr_id,
]);
}else{
array_push($repeated, $arr['nationalCode']);
}
}
if(!empty($repeated)){
Session::flash('repeated',$repeated);
}