Level 73
Try this:
public function customValidationAttributes()
{
return [
'*.1' => 'country',
'*.2' => 'state',
];
}
I am using Laravel-8 and Maatwebsite-3.1 package for upload:
I have this Excel sheet:
class StateOriginImport implements ToModel, WithHeadingRow, WithStartRow, SkipsOnError, WithValidation, SkipsOnFailure
{
private $countries;
use Importable, SkipsErrors, SkipsFailures;
public function __construct()
{
$this->countries = Country::select('id', 'name', 'nationality')->get();
}
public function model(array $row)
{
$country = $this->countries->where('name', $row[1])->where('nationality', $row[1])->first();
return new StateOrigin([
'country_id' => $country->id ?? NULL,
'name' => $row['2'],
'created_at' => date("Y-m-d H:i:s"),
'created_by' => Auth::user()->id,
]);
}
public function headingRow(): int
{
return 1;
}
public function startRow(): int
{
return 2;
}
public function customValidationAttributes()
{
return [
'*.1' => 'Country',
'*.2' => 'State Of Origin',
];
}
public function rules(): array
{
return [
'*.1' => [
'required',
],
'*.2' => [
'required',
'string',
'max:100',
Rule::unique('state_origins')->where(function ($query) {
return $query->where('country_id', '*.1');
})
],
];
}
public function batchSize(): int
{
return 1000;
}
public function chunkSize(): int
{
return 1000;
}
}
The header is to be skipped. Country is a foreign key. When I submitted, I got this error, stating that it didn't see any of the rows:
{
"message": [{
"row": 2,
"attribute": "Country",
"errors": [
"The Country field is required."
],
"values": {
"country": "Ghana",
"state": "Accra"
}
},
{
"row": 2,
"attribute": "State Of Origin",
"errors": [
"The State Of Origin field is required."
],
"values": {
"country": "Ghana",
"state": "Accra"
}
},
{
"row": 3,
"attribute": "Country",
"errors": [
"The Country field is required."
],
"values": {
"country": "Ghana",
"state": "Kumasi"
}
},
{
"row": 3,
"attribute": "State Of Origin",
"errors": [
"The State Of Origin field is required."
],
"values": {
"country": "Ghana",
"state": "Kumasi"
}
},
{
"row": 4,
"attribute": "Country",
"errors": [
"The Country field is required."
],
"values": {
"country": "Ghana",
"state": "Ashante"
}
},
{
"row": 4,
"attribute": "State Of Origin",
"errors": [
"The State Of Origin field is required."
],
"values": {
"country": "Ghana",
"state": "Ashante"
}
}
],
}
Where have I missed it, and how do I resolve it?
Thanks
Please or to participate in this conversation.