Level 102
Why convert to collection? Laravel excel has built in validation to check each row https://docs.laravel-excel.com/3.1/imports/validation.html#handling-validation-errors
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm trying to import students grades in this steps below, but it takes log time to finish processing!! uploading steps:
public function importStudentGrades(Request $request, Study $study)
{
$columns = $study->marks()->select('marks.id', 'short_name', 'max')->get();
//To read imported excel from storage_path
$users = Excel::toCollection(new StudyStudentGradesImport,
storage_path('uploads/students-grades-stady-'.$study->id.'.xlsx'));
foreach ($users[0] as $user) {
$student = DB::table('users')->select('id','code')->whereCode($user['code'])->first();
$user['note'] = [];
$notes=[];
foreach ($columns as $column) {
$key = strToLower($column->short_name);
$key = str_replace(' ','_',$key);
error_log("keeeeeeeeeeeeeeeeeeeeeey");
error_log(json_encode($key));
if(isset($user[$key])){
// grade must be numeric or null
if( !is_numeric($user[$key]) && $user[$key] !== NULL ){
array_push( $notes,'Error: (' . $column->short_name.') Grade must be numeric value.' );
}elseif((!is_int($user[$key]) || $user[$key] == 0) && $user[$key] !== NULL){
$user[$key] = number_format($user[$key], 2, '.', '');
}
// grade must be within valid range
if ( $user[$key] > $column->max ) {
$submit_button = false;
array_push( $notes,'Error:(' . $column->short_name.') Grade exceeds (' . $user[$key] . ')
maximum grade (' . $column->short_name . ':' . $column->max . ')');
}
}else{
$submit_button = false;
return response(['error' => 'Grade exceeds (' . $key . ')'], 500);
}
$user['note']=$notes;
}
}
return response(['status' => true, 'users' => $users, 'submit_button'=> $submit_button], 200);
}
This is the response:
{
"status": true,
"users": [
[
{
"bn": null,
"code": 201900445,
"student_name": "Charlotte William",
"fw": "fff",
"fo": "3633.55",
"fe": 9,
"w": 28,
"total": 102.55,
"": null,
"note": [
"Error: (FW) Grade must be numeric value.",
"Error:(FO) Grade exceeds (3633.55) maximum grade (FO:50)"
]
},
{
"bn": null,
"code": 201900590,
"student_name": " Oliver James",
"fw": " ",
"fo": 666,
"fe": 23,
"w": 30,
"total": 103,
"": null,
"note": [
"Error: (FW) Grade must be numeric value.",
"Error:(FO) Grade exceeds (666) maximum grade (FO:50)"
]
},
]
]
}
How can this method be improved to be faster? thanks
Please or to participate in this conversation.