Validation: Sometimes|Required

Posted 2 months ago by theFundi

Hey Guys, iv bashed my head around for a good few hours trying to figure this out and its time I ask for some help.

I have created a basic password reset feature but I cannot get the validation to work correctly. If the user does not complete the 'current_password' input then the validation should not take effect, but it does.

I constantly get the "The current password field is required." validation error.

Input Field:

<div class="row">
    <div class="col-md-4 form-group">
        <label>Current Password</label>
        <input id="current_password" name="current_password" type="password" autocomplete="new-password" class="form-control">
    </div>
    <div class="col-md-4 form-group">
        <label>New Password</label>
        <input id="password" type="password" name="password" class="form-control" autocomplete="new-password">
    </div>
    <div class="col-md-4 form-group">
        <label>Confirm New Password</label>
        <input id="password_confirmation" type="password" name="password_confirmation" class="form-control" autocomplete="new-password">
    </div>
</div>

Validation Logic:

protected function validationRules()
{
    return [
        'email' => 'sometimes|required|email|unique:users,email,'.auth()->user()->id,
        'current_password' => 'sometimes|required|min:8',
        'password' => 'sometimes|required|min:8',
    ];
}

Update Logic:

public function update(Request $request)
{
    $user = auth()->user();

    $atts = request()->validate($this->validationRules(), $this->validationErrorMessages());

    if( request('current_password') !== null ) {
        if(Hash::check(request('current_password'), $user->password)){
            return redirect('/profile')->with('error', 'Password update failed. Please ensure your have entered your current password correctly.');
        }

        $atts['password'] = Hash::make($request->password);
        };

        $user->update($atts);

        return redirect('/profile')->with('success', 'Your account details have successfully been updated');
    }

Reference: https://laravel.com/docs/5.4/validation#conditionally-adding-rules

Please sign in or create an account to participate in this conversation.