Code Below, basic example, but I want to return errors (see commented out if statement after the import ). How would I pass variables from the 'import' class back to the controller?
Controller:
public function resultsImport(Request $request)
{
//validate the xls file
$this->validate($request, array('student_results_import_file' => 'required'));
if($request->hasFile('student_results_import_file')){
$extension = File::extension($request->student_results_import_file->getClientOriginalName());
if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {
Excel::import(new StudentResultsImport, $request->file('student_results_import_file'));
// if $ignore_count>0 --> do stuff
return redirect('/baadmin/students')->with('flash_message', ['success','Results Imported Successfully','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" imported successfully!']);
} else {
return redirect('/baadmin/students')->with('flash_message', ['error','Results Import Failed','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" import failed. File is a '. $extension .' file. Please upload a valid xls/csv file.']);
}
}
}
Import
public function collection(Collection $rows)
{
set_time_limit(300);
$ignore_count = 0;
foreach ($rows as $row) {
if ($row[8] != '') {
//import
}
else {
$ignore_count++;
//$ignore_count is just a simple example, ultimately would probably have an array of the various errors detected on the various rows
}
}
}
Managed to find the appropriate answer in the documentation, referring to 'Getters': https://docs.laravel-excel.com/3.1/architecture/objects.html#getters
eg:
namespace App\Imports;
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
private $rows = 0;
public function model(array $row)
{
++$this->rows;
return new User([
'name' => $row[0],
]);
}
public function getRowCount(): int
{
return $this->rows;
}
}
After doing the import, we can request the state with the getter.
$import = new UsersImport;
Excel::import($import, 'users.xlsx');
dd('Row count: ' . $import->getRowCount());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With