I'm trying to validate some input array fields in Laravel. My application reports back the field is required, even though it has been filled out.
The validation code I have is:
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'telephone' => 'required',
'email' => 'unique:contacts,email,' . $request->id,
'address' => 'required',
'address.0.address_line_1' => 'required',
]);
The full posted array is:
Array
(
[id] => 1
[_token] => xxx
[first_name] => Joe
[last_name] => Bloggs
[contact_name] => Joe Bloggs
[telephone] => 077
[email] => [email protected]
[address] => Array
(
[0] => Array
(
['address_line_1'] => sss
['address_line_2'] =>
['city'] =>
['county'] =>
['postcode'] =>
['property_type'] => site
)
)
)
My input fields are constructed like so:
address[0]['address_line_1']
I'm getting the validation message error:
The address.0.address line 1 field is required.
Anyone know what's wrong here?
CodePudding user response:
Buddy just replace your validator with this
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'telephone' => 'required',
'email' => 'unique:contacts,email,' . $request->id,
'address' => 'required',
'address.*' => 'required',
'address.*.address_line_1' => 'required',
]);
CodePudding user response:
That's because you don't have any address_line_1
or address_line_2
in your array validation but you have posted those two elements.
You only have address.0.address_line_1
and there's no address.0.address_line_1
inside your posted data.
The elements of your array validation should be the same with what you posted.
In your case, you can remove address.0.address_line_1
and add 2 more elements of your array validation.
'address_line_1' => 'required',
'address_line_2' => 'required',
The updated answer :
'address' => 'required|array',
'address.*' => 'required|array',
'address.*.address_line_1' => 'required|string',