减少Laravel中的密码验证代码

时间:2018-04-04 08:16:32

标签: php laravel

以下代码是基于用户是否在用户数据的编辑页面中输入密码来实施身份验证。

如何仅使用几种方法简化此代码?

...

    $user = User::findOrFail($id); //Get role specified by id

    if($request->password === null){
      $this->validate($request, [
        'name'=>'required|max:120',
        'email'=>'required|email|unique:users,email,'.$id
        ]);
      $request->password = $user->password;
    }

    else{
      //Validate name, email and password fields          
      $this->validate($request, [
      'name'=>'required|max:120',
      'email'=>'required|email|unique:users,email,'.$id,
      'password'=>'required|min:6|confirmed'
      ]);
    }

    $input = $request->only(['name', 'email', 'password']); //Retreive the name, email and password fields
    $roles = $request['roles']; //Retreive all roles
    $user->fill($input)->save();

...

功能

  • Laravel ver.5.6

1 个答案:

答案 0 :(得分:0)

$this->validate($request, [
  'name'=>'required|max:120',
  'email'=>'required|email|unique:users,email,'.$id,
  'password'=>'nullable|required|min:6|confirmed'
]);

在密码验证中使用nullable规则。白色保存密码使用如下代码:

if($request->password){
      $user->password = bcrypt($request->password);
}