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.
Advertisement
Answer
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.