I have a requirement wherein I need to ensure that Excel file being uploaded by user does not have duplicate rows w.r.t. 2 particular columns.
Example:
In the snippet below, I want to flag out that row 1 and 2 contain duplicate combination of COMPANY_CODE
and CLERK_CODE
:
If such duplicate combination is found I want to reject the entire file being imported and let the user know where the problem is.
Any clues?
Not sure if Maat/Laravel Excel can solve this easily. So, I went ahead and created associative array with key as concatenation of two columns which I don't want to repeat in Excel.
Then I check manually using a foreach loop that if key exists in associative array, it means there is duplicate entry in Excel.
Some Sample code for reference below:
$array = Excel::toArray(new MyExcelImport(), request()->file);
$assoc_array = array();
foreach ($array[0] as $key => $value) {
$new_key = $value['company_code'] . $value['clerk_code'];
// Presence of combination of company_code and clerk_code in the assoc_array indicates that
// there is duplicate entry in the Excel being imported. So, abort the process and report this to user.
if (array_key_exists($new_key, $assoc_array)) {
return response()->json("Combination of company_code: " .
$value['company_code'] .
" and clerk_code: " .
$value['clerk_code'] .
" is duplicate in the file being imported. Please correct same and retry upload.", 422);
}
$assoc_array[$new_key] = $value;
}
Hope this helps someone with similar needs!