Search code examples
laravellaravel-5maatwebsite-excel

(Illegal string offset) for import data to database


I'm trying to import an excel to my database table 'barangs' but it has an error saying "Illegal string offset 'kode_barang'". i dont know again to fix this error.

import data from excel to database with laravel maatwebsite

my controller

public function import(Request $request)
    {
      $this->validate($request,[
        'select_file' => 'required|mimes:xls,xlsx'
      ]);
      $path = $request->file('select_file')->getRealPath();
      $data = Excel::load($path)->get();
      if ($data->count() > 0) {
        foreach ($data->toArray() as $key => $value) {
          foreach ($value as $row) {
            $insert_data[] = array(
              'kodeBarang'  => $row['kode_barang'],
              'namaBarang'  => $row['nama_barang'],
              'stock'       => $row['stock'],
              'hargaJual'   => $row['harga_jual'],
              'kategory'    => $row['kategory']
            );
          }
        }
        if (!empty($insert_data)) {
          barang::table('barangs')->insert($insert_data);
        }
      }
      return back()->with('success','berhasil di upload');
    }

and i get error message like this

Illegal string offset 'kode_barang'

in barangController.php line 55 at HandleExceptions->handleError(2, 'Illegal string offset \'kode_barang\'', 'C:\xampp\htdocs\penjualan\app\Http\Controllers\barangController.php', 55, array('request' => object(Request), 'path' => 'C:\xampp\tmp\phpE998.tmp', 'data' => object(RowCollection), 'key' => 0, 'value' => array('kode_barang' => 331211, 'nama_barang' => 'coba import', 'stock' => 2, 'harga_jual' => 3000, 'kategory' => 'Minuman', null), 'row' => 'coba import', 'insert_data' => array(array('kodeBarang' => null, 'namaBarang' => null, 'stock' => null, 'hargaJual' => null, 'kategory' => null))))


Solution

  • You can solve this issue using the following code.

        foreach ($data->toArray() as $key => $value) {
          foreach ($value as $row_key => $row) {
            $insert_data[] = array(
              'kodeBarang'  => $row[0],
              'namaBarang'  => $row[1],
              'stock'       => $row[2],
              'hargaJual'   => $row[3],
              'kategory'    => $row[4]
            );
          }
        }