0

I have an incoming post data from js like this

[form] => Array (
    [name] => 'a form'
    [type] => 'form'
    ...
    [children] => Array (
        [0] => 
        [1] => 
        [2] => Array(
            [title] => 'first'
            [order] => '1'
            ...
        }
        [3] => Array(
            [title] => 'second'
            [order] => '2'
            ...
        )
        ...
    )
    ...
)

and rules like

[
    'form.name' => 'required|string',
    'form.type' => 'required|string',
    ...
    'form.children.*.title' => 'requered|string'
    'form.children.*.order' => 'requered|integer'
    ...
]

What is the best way to completely exclude/skip the form.children arrays that are empty and process the ones with data?

2
  • 1
    if they're nullable, they're not required. replace "required" with "nullable" Commented Dec 12, 2020 at 9:17
  • @MrEvers unfortunately they are. That is actually why I was asking. Commented Dec 12, 2020 at 9:52

2 Answers 2

1

Try this:

[
    'form.name' => 'required|string',
    'form.type' => 'required|string',
    ...
    'form.children.*.title' => 'sometimes|string'
    'form.children.*.order' => 'sometimes|integer'
    ...
]

Sometimes means, if there is something, follow the next rule(s).

https://laravel.com/docs/8.x/validation#validating-when-present

Addition:

For more complex situations, f.ex. you are not interested in an order value if there is no title, makes sense right? Try this:

[
    'form.name' => 'required|string',
    'form.type' => 'required|string',
    ...
    'form.children.*.title' => 'sometimes|string'
    'form.children.*.order' => 'exclude_if:form.children.*.title,null|integer'
    ...
]

I have never tested/used this on arrays though.

Sign up to request clarification or add additional context in comments.

Comments

0

I managed to completely remove the empty arrays just by filtering them out of the request with laravel's prepareForValidation() method and array_filter(). Worked great for me.

protected function prepareForValidation()
{
    $this->merge([
        "form" => [
            "children" => array_filter($this->form["children"])
        ]
    ]);
}

@DimitriMostrey's answer worked as well. His answer is a shorter solution without an additional method. Will accept his answer so anyone facing a similar situation can pick the one that suits the most.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.