Search code examples
phplaravelvalidationcsvmaatwebsite-excel

Laravel: Importing CSV - validation


I am trying to validate a file that I want to insert in my db through a form. The file should be "csv" and its content to be validated as well.

Here is the import method in the controller that handles the form:

public function importFromCsv(array $data) {
    if (Input::hasFile('import_file')) {
        $path = Input::file('import_file')->getRealPath();

        $data = Excel::load($path, function($reader) {
            //...
        })->get();

        $this->validator = new QuoteValidator();

        $this->validate($data);

        if (!empty($data) && $data->count()) {

            foreach ($data as $key => $value) {
                $insert[] = [
                    'content' => $value->content, 
                    'created_at' => $value->created_at,
                    'updated_at' => $value->created_at
                ];
            }

            if (!empty($insert)) {
                DB::table('quotes')->insert($insert);
            }
        }
    }
    return true;
}

The validate method:

public function validate(array $data) {
    $this->validator = Validator::make($data, $this->rules, $this->messages);

    if ( $this->validator->fails() ) {
        $exception = new InvalidDataException();
        $errors = $this->_parseMessages();
        $exception->setErrors($errors);
        throw $exception;
        }
}

The error I got:

ErrorException in QuoteService.php line 123: Argument 1 passed to App\Services\QuoteService::validate() must be of the type array, object given, called in /var/www/html/Acadia/app/Services/QuoteService.php on line 233 and defined


Solution

  • The variable you are passing to the validate method is a Collection Object (Documentation), but your validate method expects an array.

    Before you pass the data to your validate method you have to convert it to an array. You could do that by calling the method toArray()

    Example:

    $data = Excel::load($path, function($reader) {
         //...
    })->get()->toArray();