Hello,
Using laravel 12 and the package: Laravel Excel.
https://docs.laravel-excel.com/3.1/imports/validation.html
I have an excel file with these column names:
Batch, Time, Profile, Beans, In (g), Out (g)
I need to check that the value in the 'Beans' column exists in the database and that there is a value in the 'Out (g)' column.
The documentation says:
"Configuring the validator
If you want to add conditional validation or complex validation that cannot be expressed through rules you can configure the validator similar to how you would do this with a Form request (opens new window)
Manual validation
You can use $validator->getData() to get access to the data under validation
class UsersImport implements WithValidation
{
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
// or...
$validator->sometimes('*.email', 'required', $this->someConditionalRequirement());
}
}
"
When I test it, I get this error:
TypeError
vendor\maatwebsite\excel\src\Validators\Failure.php:36
Maatwebsite\Excel\Validators\Failure::__construct(): Argument #1 ($row) must be of type int, string given, called in C:\wamp64\www\mysite.local\vendor\maatwebsite\excel\src\Validators\RowValidator.php on line 55
In my blade:
@if ($errors->any())
<div class="alert alert-danger">
<p>There are errors in the file you uploaded</p>
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
My Import class:
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use App\Models\GreenBean;
class RoastImport implements ToCollection, WithHeadingRow, WithValidation
{
private $bean;
/**
* @param Collection $rows
*/
public function collection(Collection $rows)
{
foreach ($rows as $row) {
$this->bean = GreenBean::where('name', $row['beans'])->first();
}
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'out_g' => 'required',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (!$this->bean) {
$validator->errors()->add('Green Bean', 'The Green Bean is invalid');
}
});
if ($validator->fails()) {
return redirect()->route('warehouse.upload-roasts');
}
}
public function customValidationMessages()
{
return [
'out_g.required' => 'The :attribute column cannot be empty',
];
}
}
Can anyone please help?