I import records using the Laravel/Excel library. Everything works fine but I would like to get the total number of records imported when the action is performed.
How can I get this data?
I currently have the following code:
Import class where I define the variable $numrows that is increased for each iteration in the import process and I create a getter method to obtain the data stored in it from the controller.
private $numrows = 0;
public function collection(Collection $rows)
{
$cod_cliente = auth()->user()->client->id;
foreach ($rows as $row)
{
$this->$numrows++;
/*Asignación de Cód Employee */
$cod_employee = 'CNT-' . $cod_cliente . '-' . $row['cod_employee'];
$sex = ucfirst($row['sex']);
Employee::create(
[
'cod_employee' => $cod_employee,
'sex' => $sex,
'age' => $row['age'],
'birth_date' => $row['birth_date'],
'educational_level' => $row['educational_level'],
'num_children' => $row['num_children'],
'client_id' => $cod_cliente
]
);
}
}
public function getRowCount(): int
{
return $this->numrows;
}
Controller that validates the existence of a file to import and obtains the number of imported records. But here it tells me that the variable $numrows is not defined.
public function importEmployees(Request $request)
{
$validatedData = $request->validate(
[
'file' => 'required',
]
);
try {
$import = new EmployeesImport();
Excel::import($import, request()->file('file'));
$totalreg = $import->getRowCount();
Log::info(
"¡¡Importación de registros!!. La importación de empleados se ha completado."
);
return redirect()->back()->with(
'success', 'Datos importados correctamente.'
);
} catch (\Throwable $th) {
Log::error(
"¡¡ERROR!!. Proceso de importación no completado. Error: "
. $th->getMessage()
);
return redirect()->route('admin.employees.index')->with(
'error', 'Error de importación. Contacte con el administador del sistema. '
. $th->getMessage()
);
}
}
All the best.
Apparently there is no preset function that can be used to get that data.
Even so, in the laravel-excel documentation itself they explain how to do it by creating the
getRowCount()
.The steps for it are in this link: https://docs.laravel-excel.com/3.1/architecture/objects.html#getters
And once done we can execute this method:
Update
After implementing this solution and modifying the initial question, there was a new typo that appears in the final question, where this should be changed:
For this: