I tried to dd($inserts) but it shows me "[]". Here is my code in my controller.
public function importExcel()
{
$path = Input::file('import_file')->getRealPath();
$inserts = [];
Excel::load($path, function($reader) use ($inserts) {
foreach ($reader->toArray() as $rows) { // <-- $rows pertains to array of rows
foreach($rows as $row) { // <-- $row pertains to the row itself
$inserts[] = ['title' => $row['title'], 'description' => $row['description']];
}
}
});
dd($inserts);
return back();
}
Since it seems you have "rows" instead of only a "row", you need to iterate through those rows again.
Excel::load($path, function($reader) use ($inserts) {
foreach ($reader->toArray() as $rows) { // <-- $rows pertains to array of rows
foreach($rows as $row) { // <-- $row pertains to the row itself
$inserts[] = ['title' => $row['title'], 'description' => $row['description']];
}
}
});
Actually you can just do this.
$rows = $reader->toArray();
foreach($rows as $row) { // <-- $row pertains to the row itself
$inserts[] = ['title' => $row['title'], 'description' => $row['description']];
}
Or if you want to stick with get
which I think returns a collection.
$rows = $reader->get();
foreach($rows as $row) {
$inserts[] = ['title' => $row->title, 'description' => $row->description];
}
UPDATE
For the modification of $inserts
array be reflected, you need to pass its reference.
function($reader) use (&$inserts) {
// ^-- add this to pass its reference.