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

视图中我将待验证字段命名为 account。

resources/views/auth/login.blade.php

{{ csrf_field() }} {{--账号--}}
@if ($errors->has('account')) {{ $errors->first('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($this->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/Controllers/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';
    }
}

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