3

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;
}
Agu V
  • 2,091
  • 4
  • 25
  • 40

1 Answers1

8

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.

aynber
  • 22,380
  • 8
  • 50
  • 63