Laravel sometimes validation rule

I try to check the password field only if it is present. I want to allow someone to edit the user, and they may or may not want to change the user password. Therefore, I thought that I could use the Laravels validation rules, in particular the "sometimes" rule. I have this rule set:

$this->validate($request, [ 'password' => 'sometimes|required|min:8', ]); 

This is simplified for example, usually there will be different rules for other fields and more stringent rules for a password. I expect this to apply the min: 8 rule only if the password field is present in the transmitted data, but if I leave the password field empty, I will receive a validation error indicating that a password field is required.

I am not sure what I do not understand in the docs. Do I need to manually delete the password field before validation, if it was entered in the form of a form like this?

 $data = $request->all(); if ('' === $data['password']) { unset($data['password']) } 

... and then pass the array to the validator. I think this makes sense, but I can make with some confirmation that I understand correctly. Thanks in advance.

+7
php validation laravel
source share
4 answers

Documents do not specify, but deletion required makes it work.

 $this->validate($request, [ 'password' => 'sometimes|min:8', ]); 
+6
source share

I think we should say laravel. If the password is not empty, otherwise the rules will do nothing.

 $this->validate($request, [ 'password' => $request->password != null ?'sometimes|required|min:8': '' ]); 
+10
source share

I think it is generally safer to allow the user to change his password only if he can provide the old one.

Allowing the connected user to change their password without providing the old one can be a security issue.

Typically, I allow user password changes using Laravel:

  $this->validate($request, [ 'user.old_password' => [], 'user.password' => [ 'required_with:user.old_password', 'min:6', 'confirmed', 'regex:/^(?=.*[az])(?=.*[AZ])(?=.*\d)(?=.*([ -+_!@ #$%^&*.,;?])).+$/', 'different:user.old_password' ], 'user.password_confirmation' => ['required_with:user.password'], ]); 

This does not check the old password, because we don’t care, the database will check it for us, but I only check the new password if the old one.

+3
source share

In edit mode, you fill in the password field, for example, "********" and in update mode, confirm this as

 $this->validate($request, [ 'password' => 'required|min:8', ]); 

and in control check $data['password']='********' find the old password and

 $data['password']='old password in db' 

and $data['password']!='********' update pssword

+2
source share

All Articles