0

I have the following input

{
    "password":"password",
    "environment_roles":[
        {
            "environment_id":"",
            "role_id":""
        }
    ],
    "admin":true    
}

and have a Request class with following rules :

 public function rules()
    {
        return [
            'password'                              => 'required|min:6|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/',
            'environment_roles'                     => 'array',
            'environment_roles.*.role_id'           => 'required_if:admin,false|exists:roles,role_id',
            'environment_roles.*.environment_id'    => 'required_if:admin,false|exists:environment,environment_id',
            'admin'                                 => 'sometimes'
        ];
    }

But it is showing the following validation error if I give the above input, which has admin as true.

"validation": {
            "environment_roles.0.role_id": [
                "The selected environment_roles.0.role_id is invalid."
            ],
            "environment_roles.0.environment_id": [
                "The selected environment_roles.0.environment_id is invalid."
            ]
        },

How can I fix this. I need to validate the environment_roles.*.role_id and environment_roles.*.environment_id when the value for admin is true.

2
  • 1
    shows what validation message? Commented Nov 8, 2020 at 9:15
  • 1
    have you looked into the exclude_if and exclude_unless rules? Commented Nov 8, 2020 at 9:22

1 Answer 1

2

If you are always sending the admin prop it would be more suitable to make it nullable not required. You could try with that:

public function rules()
{
    return [
        'password'                              => 'required|min:6|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/',
        'environment_roles'                     => 'array',
        'environment_roles.*.role_id'           => 'nullable|required_if:admin,false|exists:roles,role_id',
        'environment_roles.*.environment_id'    => 'nullable|required_if:admin,false|exists:environment,environment_id',
        'admin'                                 => 'bool|sometimes'
    ];
}

But your error shows that the role and the environment id's does not exist in the database ( The exists rule ). Setting those two fields to nullable means it will not trigger the exists rule.

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

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.