Agu V Agu V - 1 year ago 208
PHP Question

Scope - How to return errors from laravel excel import?

I'm using Maatwebsite/Laravel-Excel for importing some data into my laravel app.

I'm looping trought the rows of the excel, validating the data and then save it, but if I got a validation error I want to return the $error variable from outside the Excel::load() function. Is it possible?

public function import()
{
Excel::load(Input::file('excelFile'), function ($reader) {
foreach ($reader->toArray() as $row) {
if($everythingOK){
//do stuff
} else {
$errors[] = 'error';
}
}
});
return $errors;
}

Answer Source

You need to create the array beforehand, then pass it through your function with the & to be able to use it in place.

public function import()
{
    $errors = [];
    Excel::load(Input::file('excelFile'), function ($reader) use (&$errors) {
        foreach ($reader->toArray() as $row) {
            if($everythingOK){
                //do stuff
            } else {
                $errors[] = 'error';
            }
        }
    });
    return $errors;
}

Otherwise, you can return $errors within your load() function. Just make sure you declare it before your foreach, so that it has something to pass back if there are no errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download