Search code examples
phplaravellaravel-validation

Laravel validation double nested


I'm having issues with double nested validation

My form is rather large and contains some nested data. Two of the fields:

{!! Form::text('address[city]', null, [] !!}
{!! Form::text('address[country[printable_name]]', null, [] )) !!}

For example this works:

'address.city' => 'required|max:255',

but

'address.country.printable_name' => 'required|max:255|country

throws "The address.country.printable name field is required." even though it has a valid country.

If I try to print all with $request->all() I get the following:

...,"address":{"city":"Maribor","country[printable_name":"Slovenia"},...

So there is missing ] after printable_name.

If I try to print

$request->input('address.country.printable_name')

I don't get anything, but it works when I try this:

$request->input('address')["country[printable_name"]

Did I do something wrong, is this not supported in Laravel or a bug? Either way, how can I get it work?

A workaround would be this

'boat.country[printable_name' => 'required|max:255',

but if I leave this the next developer to look at the code will probably want to kick my ass.


Solution

  • If you want to nest array items in request parameters you should do it like this:

    {!! Form::text('address[country][printable_name]', null, []) !!}
    

    Then you can access them as you've initially tried:

    $request->input('address.country.printable_name')
    

    Just think of structuring it as you would access it in an associative array in PHP. If you pass a parameter with this name in your form:

    address[country][printable_name]
    

    Then using plain PHP you would access it like this:

    $_REQUEST['address']['country']['printable_name'];
    

    The above example illustrates the equivalent structure.