Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

geekshubh's avatar

Send Emails using foreach loop

I have two database tables, one is for attendance, and another attendance_status, attendance_status has a foreign key which refers to id in attendance table, what I am trying to do is retrieve all the Attendance status for particular attendance_id and send the "status" for each individual student using a foreach loop, but this process is very slow and also sends 3 emails to one student instead of 1. Can anyone help me to better this code and also fix the above mentioned problem?

$attendance_id = $attendance_status->attendance_id;
          $student_id = AttendanceStatus::where('attendance_id', $attendance_id)->pluck('student_id');
          $attendance_date = Attendance::where('id',$attendance_id)->pluck('date')->first();
          $attendance_subject = Attendance::where('id',$attendance_id)->pluck('subject_id')->first();
          $subject_name = Subjects::where('id',$attendance_subject)->pluck('title')->first();
          foreach($student_id as $value => $student_id)
          {
            $status = AttendanceStatus::where('student_id', $student_id)->pluck('status')->first();
            $student_name = User::where('id',$student_id)->pluck('name')->first();
            $email = User::where('id',$student_id)->pluck('email')->first();
            Mail::send('emails.attendance.daily_attendance',['attendance_date'=>$attendance_date,'subject_name'=>$subject_name,'status'=>$status,'student_name'=>$student_name] ,function ($message) use($email, $attendance_date)
            {
              $message->subject("Attendance for ".$attendance_date);
              $message->to($email);
            });
          }
0 likes
1 reply
realrandyallen's avatar

If you have your Eloquent relationships setup properly there's no need to pluck all the fields and also query for each student. You should be able to get away with something like this:

$attendance = AttendanceStatus::with('student')->where('attendance_id', $attendance_status->attendance_id)->get();

$attendance->map(function($item) {
     Mail::send('emails.attendance.daily_attendance', ['data' => $item], function ($message) use ($item)
          $message->subject("Attendance for " . $item->attendance_date);
          $message->to($item->student->email);
     });
});

Just make sure in your email view emails.attendance.daily_attendance that you change the fields to use the $data variable: like $data->attendance_date

Please or to participate in this conversation.