简体   繁体   English

Laravel 5使用Attempt方法使用用户名或电子邮件自定义登录

[英]Laravel 5 custom login with username OR email using the Attempt method

In my laravel app, at the start I had decided to create my own custom login controller, rather than use the base one. 在我的laravel应用中,一开始我决定创建自己的自定义登录控制器,而不是使用基本的控制器。

public function postSignin(Request $request, AppMailer $mailer) {
    $this->validate($request, [
        'email' => 'required',
        'password' => 'required',
    ]);     

    if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
        return redirect()->back()->with('info', 'Could not sign you in with those details.');
    }

    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'verified' => 0]))
    {
        $mailer->sendEmailConfirmationTo(Auth::user());
        Auth::logout();
        return redirect()->back()->with('info', 'Email verification required.');
    }

    Auth::user()->last_login = new DateTime();
    Auth::user()->save();       

    return redirect()->back()->with('info', 'You are now signed in.');
}   

And now I want to edit this so that users can also login with their usernames and not just their emails, using the same field. 现在,我想对此进行编辑,以便用户也可以使用同一字段使用用户名登录,而不仅仅是电子邮件登录。 However, the attempt method is confusing. 但是,尝试方法令人困惑。 It seems to expect an email even after I switch the values around. 即使我更改了这些值,似乎也希望收到一封电子邮件。

The Auth documentation isn't very helpful in this case either. 在这种情况下,Auth文档也不是很有用。 It asks me to add this: 它要求我添加以下内容:

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

in the login controller, but obviously this is for a default setup. 在登录控制器中,但显然这是默认设置。

You can use the ' FILTER_VALIDATE_EMAIL ' checker. 您可以使用“ FILTER_VALIDATE_EMAIL ”检查器。

$username = $request->get('username');
$password = $request->get('password');
$remember_me = $request->get('remember_me','1');

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

if(Auth::attempt([$field => $username,'password' => $password],$remember_me)){
    //Auth successful here
}

Meaning FILTER_VALIDATE_EMAIL do check the string whether it is in email format or not. 含义FILTER_VALIDATE_EMAIL会检查字符串是否为电子邮件格式。

I hope this sample code helps you. 希望该示例代码对您有所帮助。

-ken

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM