Laravel 5:仅在更改密码输入时更改密码

时间:2016-06-22 13:51:45

标签: php laravel-5 updatemodel

我目前正在使用Laravel应用程序上的用户编辑表单,它包含一个密码输入。目前,每次单击更新按钮,即使不更改当前密码,也会更新密码。我希望密码重置仅在有输入时发生。以下是我的代码:

用户控制器

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

2 个答案:

答案 0 :(得分:0)

也许你可以试试

$data = $request->all();
if( empty( $data['password'] ) ){
    unset($data['password']);
}
User::find($id)->update($data);

我经常处理这个问题。祝你好运。

答案 1 :(得分:0)

刚刚解决了我自己的问题。模型没有问题,我更专注于控制器。我根据请求创建了新变量,因此newpassword和verifypassword字段将是明确的。它们都是匹配的,如果它是正确的,它将给出一个新的输入。在模型中,密码是加密的,因此无需在控制器中使用bcrypt。

我希望这有助于其他人遇到类似问题,并希望在同一表单中使用验证输入更新密码。

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