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

ErikRobles's avatar

Laravel 8 Undefined Offset: 1 on second iteration of loop

Hello. I am creating an attendance app in Laravel 8 where a teacher can register many students for one day in an array loop. Everything loads into the db perfectly on the first loop iteration but on the second iteration, the program throws an error and only submits the first record. I am not sure where to look for the error on this other than the line indicated by the error which is the company_id $request. If anyone can point me in the right direction on this, I would sure appreciate it. Thank you in advance. Here is my code so far - AttendanceController.php

public function AttendanceTeacherReportStore(Request $request) {
        $countstudent = count($request->student_id);
        if($countstudent !=NULL) {
            for($i=0; $i < $countstudent; $i++) { 
                $attend = new Attendance();
                $attend->student_id = $request->student_id[$i];
                $attend->teacher_id = Auth::user()->id;
                $attend->attend_status = $request->attend_status[$i];
                $attend->date = $request->date;
                $attend->company_id = $request->company_id[$i];
                $attend->save();
            }
        }
        $notification = array(
            'message' => 'Students Attendance Successfully Submitted.
            Feel free to add another.',
            'alert-type' => 'success'
        );
        return Redirect()->back()->with($notification);
    }

In my attendance_add containing the store form, I have the following:

@extends('admin.admin_master')
@section('admin')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="content-wrapper p-3">
    <div class="col-md-12">
        <!-- general form elements -->
        <div class="card card-primary">
          <div class="card-header">
            <h3 class="card-title">Add Attendance</h3>
          </div>
          <!-- /.card-header -->
          <!-- form start -->
          <form action="{{ route('admin.pages.attendance.attendance_store') }}" method="post">
            @csrf
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        
                        <div class="form-group">
                            <label for="teacher">Teacher's Name</label>
                            <input class="form-control" type="text" name="teacher_id" value="{{ Auth::user()->name; }}">
                        </div> 
                    </div>
                
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="exampleInputEmail1">Select Date</label>
                            <input class="form-control" type="date" name="date">  
                        </div>
                    </div><!--End col md 12-->
                </div><!--end row-->
                <div class="add_item">

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                          <h5>Student Name <span class="text-danger">*</span></h5>
                          <div class="controls">
                              <select name="student_id[]" required class="form-control">
                                  <option value="" selected disabled>Select Student Name</option>
                                  @foreach($students as $student)
                                      <option value="{{ $student->id }}">{{ $student->name }}</option>
                                  @endforeach
                              </select>
                          </div>
                        </div>
                          {{-- End form Group --}}    
                      </div>
                      {{-- End Col md 3 --}}
                      <div class="col-md-3">
                        <div class="form-group">
                          <h5>Attendance Status <span class="text-danger">*</span></h5>
                          <div class="controls">
                              <select name="attend_status[]" required class="form-control">
                                  <option value="" selected disabled>Select Attendance Status</option>
                                  <option value="On Time">On Time</option>
                                  <option value="On Leave">On Leave</option>
                                  <option value="Absent">Absent</option>
                                  <option value="15 min Late">15 Minutes Late</option>
                                  <option value="30 min Late">30 Minutes Late</option>
                                  <option value="45 min Late">45 Minutes Late</option>
                                </select>
                          </div>
                        </div>
                          {{-- End form Group --}}    
                      </div>
                      {{-- End Col md 3 --}}
                      <div class="col-md-3">
                        <div class="form-group">
                          <h5>Company Name <span class="text-danger">*</span></h5>
                          <div class="controls">
                              <select name="company_id[]" required class="form-control">
                                  <option value="" selected disabled>Select Company</option>
                                  @foreach($companies as $company)
                                      <option value="{{ $company->id }}">{{ $company->name }}</option>
                                  @endforeach
                              </select>
                          </div>
                        </div>
                          {{-- End form Group --}}    
                      </div>
                      {{-- End Col md 3 --}}
                      
                      <div class="col-md-2" style="padding-top: 25px;">
                        <span class="btn btn-success addeventmore"><i class="fa fa-plus-circle"></i></span>
                      </div>
                </div><!--End Row-->
            </div><!--End add_item row-->
            </div>
            <!-- /.card-body -->


            <div class="card-footer">
              <button type="submit" class="btn btn-primary">Submit Attendance</button>
            </div>
          </form>
        </div>
        <!-- /.card -->

    </div>
</div>
</div>

<div style="visibility: hidden;">
    <div class="whole_extra_item_add" id="whole_extra_item_add">
      <div class="delete_whole_extra_item_add" id="delete_whole_extra_item_add">
        <div class="form-row">
            <div class="col-md-3">
                <div class="form-group">
                  <h5>Student Name <span class="text-danger">*</span></h5>
                  <div class="controls">
                      <select name="student_id[]" required class="form-control">
                          <option value="" selected disabled>Select Student Name</option>
                          @foreach($students as $student)
                              <option value="{{ $student->id }}">{{ $student->name }}</option>
                          @endforeach
                      </select>
                  </div>
                </div>
                  {{-- End form Group --}}    
              </div>
              {{-- End Col md 3 --}}
        
              <div class="col-md-3">
                <div class="form-group">
                  <h5>Attendance Status <span class="text-danger">*</span></h5>
                  <div class="controls">
                      <select name="attend_status[]" required class="form-control">
                          <option value="" selected disabled>Select Attendance Status</option>
                          <option value="On Time">On Time</option>
                          <option value="On Leave">On Leave</option>
                          <option value="Absent">Absent</option>
                          <option value="15 min Late">15 Minutes Late</option>
                          <option value="30 min Late">30 Minutes Late</option>
                          <option value="45 min Late">45 Minutes Late</option>
                        </select>
                  </div>
                </div>
                  {{-- End form Group --}}    
              </div>
              {{-- End Col md 3 --}}
              <div class="col-md-3">
                <div class="form-group">
                  <h5>Company Name <span class="text-danger">*</span></h5>
                  <div class="controls">
                      <select name="comopany_id[]" required class="form-control">
                          <option value="" selected disabled>Select Company Name</option>
                          @foreach($companies as $company)
                              <option value="{{ $company->id }}">{{ $company->name }}</option>
                          @endforeach
                      </select>
                  </div>
                </div>
                  {{-- End form Group --}}    
              </div>
              {{-- End Col md 3 --}}
          <div class="col-md-2" style="padding-top: 25px;">
            <span class="btn btn-success addeventmore"><i class="fa fa-plus-circle"></i></span>
            <span class="btn btn-danger removeeventmore"><i class="fa fa-minus-circle"></i></span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    $(document).ready(function() {
      let counter = 0;
      $(document).on("click", ".addeventmore", function () {
        let whole_extra_item_add = $('#whole_extra_item_add').html();
        $(this).closest(".add_item").append(whole_extra_item_add);
        counter++;
      });
      $(document).on("click", ".removeeventmore", function (event) {
        $(this).closest(".delete_whole_extra_item_add").remove();
        counter -= 1;
      });
    });
  </script>
@endsection

As you can see, I am adding an form element to the array using javascript. I am not sure what I am missing because, like I said, I am able to register one piece of information to the db but not multiple. Thanks in advance.

0 likes
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

The issue here is because you are trying to get the company id of an index from another array size. So that might not hold the same amount of records and hence the offset error.

So $i holds the count of the student_id but the company_id obviously does not have the same size and hence this line $request->company_id[$i]; throws an error. You should either make a validation, which will check if the sizes of both arrays are the same, or require each field to be completed, otherwise you will get this error randomly, or your users will get it not knowing that each of the fields are required.

ErikRobles's avatar

@Nakov Thank you for your reply. I see your point and it makes me wonder if there might be a simpler way to do what I am tring to do. I am trying to get the teacher to be able to add either one or many students for a given day and add each record depending on how many students they add. Any thing you can think of that won't require the arrays counts to match? I may be overcomplicating it with my code. Here is the senario: In this specific teacher's case, out of 20 students, He is assigned only 4. These are the only 4 studens He can assign an attend_status to for a given day. Let's say on day 19, he can only change 3 student values because the other students don't take class that day normally. This teacher is also only assigned one or two companies. So on the 19th, he marks student A B from company X absent and Studetn C from company Y absent. I hope that clarifies my dilema. Again, thank you.

ErikRobles's avatar

@Nakov Thank you for leading me onto the right path. The solution was simple once I read through your answer a couple of times (lol). I simply removed the square brackets from the two entries in the view (company_id and attend_status) and then removed the [$i] from those in the controller and now all the data gets to the db. Thank you so much for getting me on the right track.

ErikRobles's avatar

@Nakov I'm back. In testing, I just realized that the same value is given to all records so I am not quite out of the woods yet. So, in the end, I can still get my company Id and name in the view table by using relations. I removed the company input and all is good. Thank you for your help @nakov

Please or to participate in this conversation.