允许使用 Laravel 5.4 中的用户名或电子邮件登录

Allow login using username or email in Laravel 5.4

现在我已经按照 Laravel 文档了解如何在身份验证期间允许使用用户名,但它剥夺了使用电子邮件的能力。我想允许用户使用他们的用户名或电子邮件登录。我该怎么做?

我已根据 Laravel 的文档将此代码添加到 LoginController,它只允许用户名登录。我希望它接受用户名或电子邮件登录。

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

按照此 link 中的说明进行操作:https://laravel.com/docs/5.4/authentication#authenticating-users

然后你可以像这样检查用户输入

$username = $request->username; //the input field has name='username' in form

if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
    //user sent their email 
    Auth::attempt(['email' => $username, 'password' => $password]);
} else {
    //they sent their username instead 
    Auth::attempt(['username' => $username, 'password' => $password]);
}

//was any of those correct ?
if ( Auth::check() ) {
    //send them where they are going 
    return redirect()->intended('dashboard');
}

//Nope, something wrong during authentication 
return redirect()->back()->withErrors([
    'credentials' => 'Please, check your credentials'
]);

这只是一个示例。您可以采用无数种不同的方法来实现同样的目标。

我认为更简单的方法是覆盖 LoginController 中的用户名方法:

public function username()
{
   $login = request()->input('login');
   $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
   request()->merge([$field => $login]);
   return $field;
}

我认为它更简单,只需覆盖 AuthenticatesUsers traits 中的方法,您的 LoginController 中的凭据方法。在这里,我已经实现了使用电子邮件或 phone 登录。您可以更改它以满足您的需要。

LoginController.php

protected function credentials(Request $request)
{
    if(is_numeric($request->get('email'))){
        return ['phone'=>$request->get('email'),'password'=>$request->get('password')];
    }
    return $request->only($this->username(), 'password');
}
This solution of "Rabah G" works for me in Laravel 5.2. I modified a litle but is the same

$loginType = request()->input('useroremail');
$this->username = filter_var($loginType, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$this->username => $loginType]);
return property_exists($this, 'username') ? $this->username : 'email';

谢谢,这是我得到的解决方案,谢谢你。

protected function credentials(Request $request) { 

$login = request()->input('email'); 

// Check whether username or email is being used
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'user_name'; 
return [ 
   $field    => $request->get('email'), 
  'password' => $request->password, 
  'verified' => 1 
]; 
} 

您需要从您的 LoginController 中的 \Illuminate\Foundation\Auth\AuthenticatesUsers Trait 覆盖 protected function attemptLogin(Request $request) 方法 即在我的 LoginController class

protected function attemptLogin(Request $request) {

    $identity = $request->get("usernameOrEmail");
    $password = $request->get("password");

    return \Auth::attempt([
        filter_var($identity, FILTER_VALIDATE_EMAIL) ? 'email' : 'username' => $identity,
        'password' => $password
    ]);
}

您的 LoginController class 应该使用 Trait \Illuminate\Foundation\Auth\AuthenticatesUsers 以覆盖 attemptLogin 方法,即

class LoginController extends Controller {

     use \Illuminate\Foundation\Auth\AuthenticatesUsers;
     .......
     .......
}

我是这样做的:

// get value of input from form (email or username in the same input)
 $email_or_username = $request->input('email_or_username');

 // check if $email_or_username is an email
 if(filter_var($email_or_username, FILTER_VALIDATE_EMAIL)) { // user sent his email 

    // check if user email exists in database
    $user_email = User::where('email', '=', $request->input('email_or_username'))->first();

    if ($user_email) { // email exists in database
       if (Auth::attempt(['email' => $email_or_username, 'password' => $request->input('password')])) {
          // success
       } else {
          // error password
       }
    } else {
       // error: user not found
    }

 } else { // user sent his username 

    // check if username exists in database
    $username = User::where('name', '=', $request->input('email_or_username'))->first();

    if ($username) { // username exists in database
       if (Auth::attempt(['name' => $email_or_username, 'password' => $request->input('password')])) {
          // success
       } else {
          // error password
       }
    } else {
       // error: user not found
    }
 }       

我相信有一个更短的方法可以做到这一点,但对我来说这很有效并且很容易理解。

打开您的 LoginController.php 文件。

  1. 添加此引用

    use Illuminate\Http\Request;
    
  2. 并覆盖 凭据方法

    protected function credentials(Request $request)
    {
        $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
        ? 'email'
        : 'username';
    
        return [
            $field => $request->get($this->username()),
            'password' => $request->password,
        ];
    }
    

Laravel 5.7.11

测试成功

将此代码添加到您的登录控制器 - 希望它能起作用。参考login with email or username in one field

 public function __construct()
{
    $this->middleware('guest')->except('logout');

    $this->username = $this->findUsername();
}

public function findUsername()
{
    $login = request()->input('login');

    $fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

    request()->merge([$fieldType => $login]);

    return $fieldType;
}

public function username()
{
    return $this->username;
}
public function username()
{
    //return ‘identity’;
    $login = request()->input('identity');
    $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone';
    request()->merge([$field => $login]);

    return $field;
}


protected function validateLogin(Request $request)
{
    $messages = [
        'identity.required' => 'Email or username cannot be empty',
        'email.exists' => 'Email or username already registered',
        'phone.exists' => 'Phone No is already registered',
        'password.required' => 'Password cannot be empty',
    ];

    $request->validate([
        'identity' => 'required|string',
        'password' => 'required|string',
        'email' => 'string|exists:users',
        'phone' => 'numeric|exists:users',
    ], $messages);
}

https://dev.to/pramanadiputra/laravel-how-to-let-user-login-with-email-or-username-j2h