0

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] => joe@test.com
[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?

V4n1ll4
  • 5,973
  • 14
  • 53
  • 92

3 Answers3

0

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',
zaidysf
  • 492
  • 2
  • 14
0

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',
]);
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • Thanks, but it's still failing validation saying "The address.0.address_line_1 field is required." even though it's filled. – V4n1ll4 Mar 05 '22 at 19:03
  • I'm thinking this could possibly b a bug with Laravel version 5.2.45 – V4n1ll4 Mar 05 '22 at 19:06
0

I managed to figure out what was causing the issue...it was actually to do with the form input field names.

I removed the single quotes from the input names and it worked!

I changed:

<input type="text" class="form-control" name="address[0]['address_line_1']">

To, this:

<input type="text" class="form-control" name="address[0][address_line_1]">

And it worked! Hope it helps someone else.

V4n1ll4
  • 5,973
  • 14
  • 53
  • 92