Search code examples
phplaravel-5updatemodel

Laravel 5: Password change only when password input is changed


I am currently working on a user edit form on my Laravel app and it includes a password input. Currently each time I click on the update button it updates the password even without changing the current password. I would like have the password reset happen only when there is an input. Below is my code:

User Controller

public function update(Request $request, $id)
{
   //
    $user = User::findOrFail($id); 
    $user->name = $request->get('name'); 
    $user->email = $request->get('email'); 
    $user->password = $request->get('password');

    $this->validate($request, User::validationRules());

    $user->save(); 
    return redirect('/user');     
}

User.php (Model)

public static function validationRules( $attributes = null )
{
    $rules = [
        'name' => 'required|string|max:100',
        'email' => 'required|email' 
    ];

    // no list is provided
    if(!$attributes)
        return $rules;

    // a single attribute is provided
    if(!is_array($attributes))
        return [ $attributes => $rules[$attributes] ];

    // a list of attributes is provided
    $newRules = [];
    foreach ( $attributes as $attr )
        $newRules[$attr] = $rules[$attr];
    return $newRules;
}

public function setPasswordAttribute($password)
{  
    $this->attributes['password'] = bcrypt($password); 
}

Solution

  • Just cracked my own problem. There is no problem in the model, I focused more on the controller. I created new variables based on the request so the newpassword and verifypassword fields would be clear. They are both matched and if it is correct, it will give a new input. In the model, the password is encrypted so no need to use bcrypt within the controller.

    I hope this helps others facing a similar problem and would like to have update the password with a verification input within the same form.

    public function update(Request $request, $id)
    {
        // 
        $data = $request->all(); 
    
        $userinput['name'] = $data['name']; 
        $userinput['email'] = $data['email']; 
    
        //check to see if field new password is filled. 
        if($data['newpassword']) 
        { 
          //verify that the newpassword input matches the verify password
          if($data['newpassword'] == $data['verifypassword']) {  
             $userinput['password'] = $data['newpassword']; 
          } 
    
          //else statement can be made for the case if newpassword != verifypassword
    
        }
    
        $this->validate($request, User::validationRules());
    
        User::find($id)->update($userinput);  
        return redirect('/user');     
    }