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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42708942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:41:32  来源:igfitidea点击:

Allow login using username or email in Laravel 5.4

phplaravellaravel-5.4

提问by Paul Lucero

Now I've followed the Laravel documentation on how to allow usernames during authentication, but it takes away the ability to use the email. I want to allow users to use their username or email to login. How do I go about this?

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

I've added this code to the LoginController as per Laravel's Documentation and it only allows username for login. I want it to accept username or email for login.

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

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

回答by Rabah

I think a simpler way is to just override the username method in LoginController:

我认为更简单的方法是覆盖 LoginController 中的 username 方法:

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

回答by EddyTheDove

Follow instructions from this link: https://laravel.com/docs/5.4/authentication#authenticating-users

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

Then you can check for the user input like this

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

$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'
]);

This is just a sample. THere are countless various approaches you can take to accomplish the same.

这只是一个示例。您可以采取无数种方法来完成相同的任务。

回答by Rakibul Islam

Open your LoginController.phpfile.

打开你的LoginController.php文件。

  1. Add this reference

    use Illuminate\Http\Request;
    
  2. And override the credentials method

    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,
        ];
    }
    
  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,
        ];
    }
    

Successfully tested in Laravel 5.7.11

Laravel 5.7.11 中测试成功

回答by Sheharyar Naseem

You need to override protected function attemptLogin(Request $request)method from \Illuminate\Foundation\Auth\AuthenticatesUsersTrait in your LoginController i.e. in my LoginController class

您需要在 LoginController 中覆盖Traitprotected function attemptLogin(Request $request)方法,\Illuminate\Foundation\Auth\AuthenticatesUsers即在我的 LoginController 类中

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

Your LoginController class should use Trait \Illuminate\Foundation\Auth\AuthenticatesUsersin order to override attemptLoginmethod i.e.

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

class LoginController extends Controller {

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

回答by Jagadesha NH

I think its even more simple, just override the method from AuthenticatesUserstraits, credentials method in your LoginController. Here I have implemented to login with either email or phone. You can change it to fit your needs.

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

LoginController.php

登录控制器.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');
}

回答by Maicon Gilton

This is the way I do it:

这是我这样做的方式:

// 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
    }
 }       

I believe there is a shorter way to do that, but for me this works and is easy to understand.

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

回答by Mahedi Hasan Durjoy

Add this code to your login controller - Hope it will works. Reference 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;
}

回答by Jose Villasmil

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

回答by R0bertinski

Thanks, this is the solution I got thanks to yours.

谢谢,这是我感谢您的解决方案。

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