LARAVEL Login by email or username

Asked

Viewed 881 times

1

Hello, I’m developing an application in Laravel 5.2. * and I need to implement a login system by username or login, someone has an idea of how to configure or do this type of method?

  • Related: https://answall.com/questions/162965/laravel-authatempt-sempre-retorna-false/162970#162970

  • Related: https://answall.com/questions/206213/erro-auth-laravel-com-outra-model/206227#206227

  • Related: https://answall.com/questions/148446/autentica%C3%A7%C3%A3o-costumizada-com-Cpf-e-email/151477#151477

  • The authentication system is already ready and configured just use the https://laravel.com/docs/5.4/authenticationdocumentation itself, but if you have something specific you can edit your question and explain better.

2 answers

1

Illuminate\Foundation\Auth\AuthenticatesUsers

Swap the variable for the field you want to authenticate

protected $username = 'username';

1


You can create a new login method as follows:

public function authenticate( Request $request )
{
    $password = bcrypt( $request->input( 'password' ) );
    $login    = $request->input( 'login' ); // Email ou username

    if ( Auth::attempt( ['email' => $login, 'password' => $password] ) || Auth::attempt( ['username' => $login, 'password' => $password] ) ) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    }
}
  • It is not the right way to use polyformism for this. See that in Trait Illuminate\Foundation\Auth\AuthenticatesUsers there is the method loginUsername, who searches for the property username, where it is not found, the field is returned email to be used for authentication. Whenever you need something, look at the core of Laravel.

  • @juniorb2ss please clarify a question, using the username property, can the login be done by both fields? Because I had understood the following, if using the username property the login would be performed by the field I use there, otherwise it would use the email and not both fields.

  • Read the core. If you put the property username it will use this field for the query, along with the password. If the default is email and password, you change the property username for login, the query will be made over the columns login and password. Now, if you want to complement something, it’s also possible, just overwrite the method credentials, which reserves which fields go to query.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.