Search code examples
laravellaravel-5laravel-validation

Laravel sometimes validation rule not working


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.


Solution

  • 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();
    }