Laravel 实现用户名 + 邮箱 + 手机号登录

视图中将验证字段命名为 account
resources/views/auth/login.blade.php

{{ --账号-- }}
   
@if( $errors->has('account') ) {{ $errors->has('account') }} @endif

接下来在 LoginController.php 重写 AuthenticatesUsers Trait 中的 attemptLogin()validateLogin()username() 三个方法。

  • attemptLogin() 方法:

将:

  return $this->guard()->attempt(
   $this->credentials($request, $request->filled('remember'))
  );

替换为:

return collect(['username','email','phone'])->contains( function ($value) use ($request) {
      $account = $request->get('username');
      $password = $request->get('password');
      return $this->guard()->attempt([ $value => $account, 'password' => $password ], $request->filled('remember'));
});
  • validateLogin() 方法:

主要将 $this->username() 改为中文。当然也可以添加自己的验证规则。

protected function validateLogin( Request $request)
{
    $this->validate($request, [
      $this->username() => 'required|string',
       'password' => 'required|string',
       'captcha' => 'required|captcha',
],[
       'captcha.required' => ':attribute 不能为空',
       'captcha.captcha' => '请输入正确的 :attribute',
],[
       $this->username() => '账号',
       'captcha' => '验证码',
]);
}
  • username() 方法:

不用说,将返回字段改为 account:

public function username()
{
    return 'account';
}

完整代码:
app/Http/Controller/Auth/LoginController.php

middleware('guest')->except('logout');
    }

   /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
      protected function attemptLogin( Request $request)
      {
           return collect(['username', 'email', 'phone'])->contains( function ($value) use ($request) {
                   $account = $request -> get( $this->username() );
                   $password = $request -> get('password);
                   return $this->guard()->attempt([ $value => $account, 'password' => $password], $request->filled('remember'));
           });
      }
/**
     * 登录验证.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
     protected function validateLogin( Request $request)
     {  
            $this->validate( $request, [
                 $this->username() => 'required|string',
                 'password' => 'required|string',
                 'captcha' => 'required|captcha',
            ],[
                 'captcha.required' => ':attribute 不能为空',
                 'captcha.captcha' => ' 请输入正确的 :attribute',
            ],[
                 $this->username() => '账号',
                 'captcha' => '验证码',
            ]);
     }

     public function username()
     {
          return 'account';
     }
}

最后还有一个小问题,拷贝 overtrue/laravel-lang 语言包稍作修改:

$ mkdir resources/lang/zh-CN
$ cp vendor/caouecs/laravel-lang/src/zh-CN/auth.php resource/lang/zh-CN

resources/lang/zh-CN/auth.php

 '账号或密码错误',
     ‘throttle’ => '您尝试的次数过多,请在 :seconds 秒后重试。',
];

你可能感兴趣的:(Laravel 实现用户名 + 邮箱 + 手机号登录)