F
Filament6mo ago
harps

CSV validation

Is there a way to validate the contents csv before upload and provide feedback to the user on why it failed. I can create a rule with sometihng like this.
class SurveyAuditCsvRule implements Rule
{

public function passes($attribute, $value)
{
// Open the csv file.
$file = fopen($value->getRealPath(), 'r');
// Get the headers from the first line
$csvHeaders = fgetcsv($file);

// Set the header to check for
$headers = ['survey_id', 'batch_id'];

// Check if the number of columns is correct
if (count($csvHeaders) != count($headers)) {
return false;
}

// Check if the headers are correct
foreach ($csvHeaders as $header) {
if (!in_array($header, $headers)) {
return false;
}
}

// Loop through every line of the file and check if a survey with the given id exists.
while (($line = fgetcsv($file)) !== false) {
$survey = GasPipeSurvey::find($line[0]);
if (!$survey) {
return false;
}
}

// Close the file
fclose($file);

return true;
}
}
class SurveyAuditCsvRule implements Rule
{

public function passes($attribute, $value)
{
// Open the csv file.
$file = fopen($value->getRealPath(), 'r');
// Get the headers from the first line
$csvHeaders = fgetcsv($file);

// Set the header to check for
$headers = ['survey_id', 'batch_id'];

// Check if the number of columns is correct
if (count($csvHeaders) != count($headers)) {
return false;
}

// Check if the headers are correct
foreach ($csvHeaders as $header) {
if (!in_array($header, $headers)) {
return false;
}
}

// Loop through every line of the file and check if a survey with the given id exists.
while (($line = fgetcsv($file)) !== false) {
$survey = GasPipeSurvey::find($line[0]);
if (!$survey) {
return false;
}
}

// Close the file
fclose($file);

return true;
}
}
But it only returns bool not anyway of storing or displaying errors. For example looping through the sheet and checking that record exists before it can be imported. In my scenario I have a form that allows the upload of existing records that need to be replicated with slightly different values. So the user will upload a sheet with a record ids in and I want to make sure the record ID exists before I try and create the duplicates and give the user the feedback. Alternatively the feedback could be given after the csv is submitted as results of success / failures in which case how would I do that?
0 Replies
No replies yetBe the first to reply to this messageJoin