Laravel 4 Auth::attempt using either email or username and password

…衆ロ難τιáo~ 提交于 2019-12-18 13:20:24

问题


In laravel for login attempt I generally use something like this:

if (Auth::attempt(array('email' => $usernameinput, 'password' => $password), true))
{
    // The user is being remembered...
}

Basically $usernameinput will check with email from my table.

I was thinking to do it in a different way, like there is email, username and password in my table. $usernameinput can be either email or username field in my table.

How can I Auth::attempt with a condition like:

(email==$usernameinput OR username==$usernameinput) AND password == $password

回答1:


Well, you could simply check if $usernameinput matches an email pattern and if it does, use the email field, else use the username field. This sounds reasonable because, well, you really shouldn't have any e-mail in your database that doesn't match the pattern. Something like this:

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

if (Auth::attempt([$field => $usernameinput, 'password' => $password], true)) {
    // ...
}

The other option is to extend Illuminate\Auth\Guard adding the wanted functionality and setting it as the auth component, in a new service provider.




回答2:


It can be done something like this

$field = Validator::make(array('email' => $usernameinput, array('email' => 'email'))->passes() ? 'email' : 'username';
if (Auth::attempt(array($field => $usernameinput, 'password' => $password), true)) {
    return Redirect::intended('profile');
}



回答3:


Users could use an email field as their username, and it might not match the email they used for the email field. Safer to attempt authentication twice:

if (Auth::attempt(array(
            'email'     => Input::get('email_or_username'),
            'password'  => Input::get('password')
        )) ||
    Auth::attempt(array(
            'username'     => Input::get('email_or_username'),
            'password'  => Input::get('password')
        ))) {
    // SUCCESS
} else {
    // FAILURE
}



回答4:


Here's the complete working solution: (Tested with Laravel 5.3)

Just add this method(or we can say override) into app\Http\Controllers\Auth\LoginController.php

public function login(Request $request)
    {
        $usernameinput = $request->input('email');
        $password = $request->input('password');
        $field = filter_var($usernameinput, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (Auth::attempt([$field => $usernameinput, 'password' => $password])) {
            return redirect()->intended('/');
        } else {
            return $this->sendFailedLoginResponse($request);
        }
    }


来源:https://stackoverflow.com/questions/21694983/laravel-4-authattempt-using-either-email-or-username-and-password

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!