Laravel:无法访问受保护的属性Maatwebsite \ Excel \ Collections \ RowCollection

我将xlsx导入到sql中,但是在导入时出现以下错误:

FatalThrowableError in ItemController.php line 41: Cannot access protected property Maatwebsite\Excel\Collections\RowCollection::$title 

如果有人面临同样的问题,或者知道会有什么build议,希望你能帮我find答案。

这是我的控制器部分:

  public function importExcel() { if(Input::hasFile('import_file')){ $path = Input::file('import_file')->getRealPath(); $data = Excel::load($path, function($reader) { })->get(); if(!empty($data) && $data->count()){ foreach ($data as $key => $value) { $insert[] = ['title' => $value->title, 'description' => $value->description]; //Line : 41 } if(!empty($insert)){ DB::table('items')->insert($insert); // dd('Insert Record successfully.'); } } } return back(); } 

路线部分:

 Route::post('/importExcel',[ 'uses'=>'ItemController@importExcel', 'as'=>'importExcel' ]); 

这是导入xlsx文件:

在这里输入图像说明

当我DD($数据)我看到以下数组:

 RowCollection {#464 ▼ #title: "Sheet1" #items: array:2 [▼ 0 => CellCollection {#390 ▼ #title: null #items: array:3 [▼ "title" => "Abdul" "description" => "This is Zaman" 0 => null ] } 1 => CellCollection {#410 ▼ #title: null #items: array:3 [▼ "title" => "Zaman" "description" => "This is Abdul" 0 => null ] } ] } 

这应该为你工作:

 if (Input::hasFile('import_file')){ $path = Input::file('import_file')->getRealPath(); $data = Excel::load($data, function($reader) { // Loop through all rows $reader->each(function($row) { DB::table('items')->insert([ 'title' => $row->title, 'description' => $row->description ]); }); }); } return back(); 

config/excel.php必须设置为false

你需要做这样的循环

 foreach ($data as $rows) { foreach ($rows as $row) { $insert[] = ['title' => $row->title, 'description' => $row->description]; } } var_dupmp($insert); 

你应该看到这个结果

 array(2) { [0]=> array(2) { ["title"]=> string(5) "Zaman" ["description"]=> string(13) "This is Zaman" } [1]=> array(2) { ["title"]=> string(5) "Abdul" ["description"]=> string(13) "This is Abdul" } 

然后你可以把这个数组插入到数据库中

对于更多的信息,你可以看到这个问题的答案是这样的:

https://github.com/Maatwebsite/Laravel-Excel/issues/351