-2

I am trying to import an Excel file into my table using the MaatWebsite package. But every time I get errors like these:

Illegal string offset 'Emp'

I am following this tutorial. And here is the code I have tried:

 $path = $request->file('attendance_data')->getRealPath();

 $data = Excel::load($path)->get();

 if($data->count() > 0)
 {
     foreach($data->toArray() as $key => $value)
     {
         foreach($value as $row)
         {
             $insert_data[] = array(
                 'employee_card'  => $row['Emp'],
                 'attendance_date'   => $row['Date'],
                 'attendance_time'    => $row['On'],
             );
         }
     }

     if(!empty($insert_data))
     {
         DB::table('attendance_logs')->insert($insert_data);
     }

Any help will be appreciated

theduck
  • 2,589
  • 13
  • 17
  • 23
Tanvir Ahmed
  • 969
  • 12
  • 24

1 Answers1

1

I can't comment so I've posted this as an answer.

Have you tried to die and dump the $row to check that it is an array of key => value pairs as you're expecting? The error looks to show up when trying to access a key of an array with numeric keys. This could also happen if $row is a string, as you can access string characters using a numeric index similar to an array.

$path = $request->file('attendance_data')->getRealPath();

$data = Excel::load($path)->get();

if($data->count() > 0) {

  foreach ($data->toArray() as $key => $value) {

    foreach ($value as $row) {

      // Print the data of $row to see what it actually is
      // and kill the process
      dd($row);

      $insert_data[] = array(
        'employee_card' => $row['Emp'],
        'attendance_date' => $row['Date'],
        'attendance_time' => $row['On'],
      );

    }

  }

  if (!empty($insert_data)) {

    DB::table('attendance_logs')->insert($insert_data);

  }

}

This answer looks to be related.

DanLewis
  • 102
  • 1
  • 8
  • It is better to provide the code snippet for better understanding because an explanation could lead to confusion at times. – Varun Jain Dec 04 '19 at 13:26