(非法字符串偏移)将数据导入数据库

时间:2019-07-26 07:30:35

标签: laravel laravel-5 maatwebsite-excel

我正在尝试将excel导入我的数据库表'barangs',但是出现错误消息“ Illegal string offset'kode_barang'”。我再次不知道要解决此错误。

使用laravel maatwebsite将数据从excel导入数据库

我的控制器

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');
    }

我收到这样的错误消息

  

非法字符串偏移量'kode_barang'

     在barangController.php第55行的HandleExceptions-> handleError(2,   '非法字符串偏移\'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,'值'=>数组('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)))))

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码解决此问题。

    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]
        );
      }
    }

答案 1 :(得分:0)

添加条件以检查null行。

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

foreach ($data->toArray() as $key => $value) {
  foreach ($value as $row_key => $row) {
    if(!isset($row['kode_barang'])) {
      $insert_data[] = array(
        'kodeBarang'  => $row['kode_barang'],
        'namaBarang'  => $row['nama_barang'],
        'stock'       => $row['stock'],
        'hargaJual'   => $row['harga_jual'],
        'kategory'    => $row['kategory']
      );
    }
  }
}