2

Request can contain field coord ({x: 1, y: 2}) or not contain it. For example:

Correct (without coord):

[
    'another_param' => 'value',
],

Correct:

[
    'another_param' => 'value',
    'coord' => [
        'x' => 1,
        'y' => 2,
    ],
],

Invalid (wrong format of coord):

[
    'another_param' => 'value',
    'coord' => [
        'x' => 1,
    ],
],

Whether it can be written by standard rules (without custom and closures).

My attempt:

'rules' => [
    'coord' => 'array',
    'coord.x' => 'required',
    'coord.y' => 'required',
],

But if a request don't contain coord then Error: The coord.x field is required.

4 Answers 4

3

You can use the sometimes validation rule so it only applies when the field is present.

'rules' => [
    'coord' => 'sometimes|array',
    'coord.x' => 'required',
    'coord.y' => 'required',
],
Sign up to request clarification or add additional context in comments.

4 Comments

There is also the nullable option that might be needed if the value exists but is null laravel.com/docs/5.6/validation#a-note-on-optional-fields
No, it's not working for input without "coord": the coord.x is required & the coord.y is required.
try adding sometimes|required to those two also
Phiter, then empty "coord" will be valid.
1

Not sure if it's still actual but here's how I solved it:

'rules' => [
    'coord' => ['nullable', 'array'],
    'coord.x' => 'required_unless:coord,null',
    'coord.y' => 'required_unless:coord,null',
],

Comments

0

You can require the fields when the array is provided using required_with:

'rules' => [
    'coord' => 'sometimes|array|min:1',
    'coord.x' => 'required_with:coord',
    'coord.y' => 'required_with:coord',
],

The sometimes rule allows this field to be discarded and min:1 ensures when this coord field is provided, it's not an empty array.

6 Comments

1. empty coord will be valid. 2. if I have 10 field I must write these all for each?
You could use nullable or sometimes on the coord itself. Just required_with:coord may work on all of the fields, haven't tried it
maybe, but it more ugly then write custom closure for validation
why is it more ugly? it's only a few more characters than required.
ugliness is not measured by the number of characters :)
|
-1

You can try validating the array fields as coord.*.x I mean:

'rules' => [
    'coord' => 'array',
    'coord.*.x' => 'required',
    'coord.*.y' => 'required',
],

Then if coord array has an element, x and y will be required

1 Comment

This would be valid for case, when coord is an actual array of x,y tuples, but it only contains x and y directly as elements.

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.