I tried to validate excel rows by using Validator inside Laravel Excel's import class following this laravel excel documentation But it seems the validation result not giving the results
The Controller : (i'm using livewire btw)
public function save()
{
$this->validate();
try {
$import = new OutputImport();
$import->import($this->excel);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
dd($failures);
}
}
The Import class :
class OutputImport implements ToCollection, WithStartRow, SkipsEmptyRows
{
use Importable;
protected $outputs;
protected $outputIds;
public function __construct()
{
$this->outputs = Output::where('status',1)->get();
$this->outputIds = $this->outputs->pluck('id')->toArray();
}
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
'*.0' => ['required', function(string $attribute, mixed $value, Closure $fail) {
if (!in_array($value, $this->outputIds))
$fail('Periksa dan pastikan kembali ID yang diinput.');
}],
'*.5' => 'required',
'*.6' => 'required|min:0',
'*.7' => 'required|min:0',
])->validate();
}
public function startRow(): int
{
return 2;
}
}
The excel data is there but After the validation execution it giving me no response at all How can i get the validation results ?
Create a validator instance and validate manually without throwing exceptions, via:
$validator = \Illuminate\Support\Facades\Validator::make($rows->toArray(), $rules);
if ($validator->fails()) {
// save messages wherever to access them later from your controller
$messages = $validator->errors();
} else {
// handle your import ...
}
however you can't really "return" these errors from your import, especially if the import in queued. I would recommend storing these errors in a table, or cache depending on how long you intent to store them for, and display them to the user. You could create an Import model to keep track of your imports, if you do many, with fields such as status and errors.