简体   繁体   中英

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.

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. 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.

$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.

I hope this sample code helps you.

-ken

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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