user9048585
user9048585

Reputation:

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.

Upvotes: 2

Views: 4621

Answers (2)

Sebastian
Sebastian

Reputation: 1001

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

Upvotes: 4

pspatel
pspatel

Reputation: 518

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.

Upvotes: 2

Related Questions