Agu V Agu V - 4 months ago 77
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

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.

Comments