在Laravel 5.4中允许使用用户名或电子邮件登录 [英] Allow login using username or email in Laravel 5.4

查看:167
本文介绍了在Laravel 5.4中允许使用用户名或电子邮件登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我已经遵循Laravel文档,了解如何在身份验证期间允许用户名,但是它剥夺了使用电子邮件的功能.我想允许用户使用其用户名或电子邮件登录.我该怎么办?

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的文档,我已将此代码添加到LoginController中,并且仅允许用户名登录.我希望它接受用户名或电子邮件进行登录.

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.

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

推荐答案

按照此链接中的说明进行操作:

Follow instructions from this link: 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.

这篇关于在Laravel 5.4中允许使用用户名或电子邮件登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆