2

I'm trying to implement the sometimes validation rule into one of my projects (Laravel 5.6).

I have a profile page that a user can update their name and password, but i want to make it so that if the user doesnt enter a password, it wont update that field, which is what i thought the sometimes rule was.

The complete update method i am using in my controller is below.

If i leave the password field blank, then it returns a string or min error which it shouldn't be doing.

public function update()
{
    $user = Auth::user();

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

    $user->name = request('name');
    $user->password = bcrypt(request('password'));

    $user->save();

    return back();
}

Any help would be greatly appreciated.

3
  • You shouldn't be passing the password field in request if you are not updating it. When you pass password field in request(even empty string) that validation rule will check if it's a string and if it's at least 6 character long. Commented May 30, 2018 at 10:20
  • Let me get this straight: If no password is entered, should the name still be updated? Commented May 30, 2018 at 10:59
  • @Sebastian yes, on the edit profile page Commented May 30, 2018 at 11:10

2 Answers 2

4

The problem is that if you leave the password field empty, it is still present in the request. But filled with null

Try this instead:

public function update()
{
    $user = Auth::user();

    $this->validate(request(), [
        'name' => 'required',
        'password' => 'nullable|string|min:6'
    ]);

    $user->name = request('name');

    if(!is_null(request('password'))) {
        $user->password = bcrypt(request('password'));
    }

    $user->save();

    return back();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh that makes sense, it was always going to update the password if there was no conditional ... Thank you!
2

Try to add nullable in validation rule

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

From Laravel docs:

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

2 Comments

Strange ... It works for the form, but then sets the password to nothing, it shouldnt even touch the password column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.