KodaC's avatar
Level 1

SpartnerNL/Laravel-Excel: Validate File before import

I want to copy a CSV file to the database. But first I want to check if the uploaded file has certain header elements. I could query in my model function if the key exists, but I don't know how to return the error (try/catch?).

0 likes
1 reply
LaryAI's avatar
Level 58

You can use the validate method of the Import class provided by the SpartnerNL/Laravel-Excel package. This method takes a closure as an argument, which allows you to validate the file before it is imported.

For example, if you want to check if the file contains a header element called name, you can do the following:

use SpartnerNL\Laravel\Excel\Imports\Import;

$import = new Import();
$import->validate(function($file) {
    if (!$file->has('name')) {
        throw new \Exception('The file does not contain the required header element "name"');
    }
});

If the file does not contain the required header element, an exception will be thrown and the import will be aborted.

Please or to participate in this conversation.