I am trying to validate a password field only if it is present. I want to allow someone to edit a user and they may or may not want to change the users password. So I thought I could this using Laravels validation rules, specifically the 'sometimes' rule. I have this set of rules:
$this->validate($request, [
'password' => 'sometimes|required|min:8',
]);
This is simplified for the example, there will usually be other rules for other fields and stricter rules for the password. I expect this to only apply the min:8 rule if the password field is present in the passed data, but if I leave the password field empty I get a validation error saying the password field is required.
I'm not sure what I'm not understanding in the docs. Do I need to manually remove the password field before validation if it is the form input was submitted empty like this?
$data = $request->all();
if ('' === $data['password']) {
unset($data['password'])
}
...and then pass the array into the validator. I think this makes sense but I could do with some confirmation that I'm understanding it correctly. Thanks in advance.