1 year ago

Validation: Sometimes|Required

Posted 1 year 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 class="col-md-4 form-group">
        <label>New Password</label>
        <input id="password" type="password" name="password" class="form-control" autocomplete="new-password">
    <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">

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


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


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