Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vlauciani's avatar

L8 - API - Form Request on optional input JSON object

Hi all

I'm working on Form Request and I've a question about how to use it with optional input object.

My API get a simple input JSON like:

{
    "user": [
        {
            "name": "Valentino",
            "car": {
                "model": "ferrari",
                "color": {
                    "front": "red",
                    "back": "black"
                }
            }
        },
            "name": "Stefano",
            "car": {
                "model": "mercedes"
            }
        }
    ]
}

the Controller:

public function insertUser(StoreUserRequest $request) {
}

the For Request Validation Class:

public function rules()
{
  return [ 
    'user' => 'required|array',
    'user.*.name' => 'string|required',
    'user.*.car' => 'required|array', 
    'user.*.car.model' => 'required|string', 
    'user.*.car.color' => 'nullable|array',  // could be present or not 
    'user.*.car.color.front' => 'required|string',  // should be validated only if exists 'color'
    'user.*.car.color.back' => 'required|string', // should be validated only if exists 'color'
  ];
}

the color object could be optional into the input JSON; how I can set StoreUserRequest.php class to validate the color object only if exists?

Thank you very much!

0 likes
1 reply
Tippin's avatar

You may be able to use the required_with rule. (have not tested directly)

public function rules()
{
  return [ 
    'user' => 'required|array',
    'user.*.name' => 'string|required',
    'user.*.car' => 'required|array', 
    'user.*.car.model' => 'required|string', 
    'user.*.car.color' => 'nullable|array',  // could be present or not 
    'user.*.car.color.front' => 'required_with:user.*.car.color|string',
    'user.*.car.color.back' => 'required_with:user.*.car.color|string',
  ];
}
1 like

Please or to participate in this conversation.