Thursday 23 August 2018

Tips Login dengan Username atau Email di Laravel


Not infrequently we include Username and Email in the registration form like this

Email:

Username:

Password:

....



then after the user has successfully registered, we usually ask to log in by including the username and password. But not infrequently can include either a Username or Email along with a password like this:


Your Email or Username ..


password ...


Sign in



So the user can log in with his username or email. This simple tip is actually possible in PHP native or in other groups.

Here's the simple way in Laravel



# AuthController.php

public function doLogin () {
 
   $ username = Input :: get ('username');
   $ password = Input :: get ('password');

   $ field = filter_var ($ username, FILTER_VALIDATE_EMAIL)? 'email': 'username';
 
   if (Auth :: attempt (array ($ field => $ username, 'password' => $ password)))
   {
      return Redirect :: intended ();
   }
   else
   {
       return Redirect :: to ('login') -> with ('error', 'Invalid username / email or password')
-> withInput ();
   }


} // end of function
       

The login form is quite normal

<input type = "text" name = "username" placeholder = "Email or username ...">
<input type = "password" name = "password" placeholder = "password ..."


Explanation:

 note the following code:

if (Auth :: attempt (array ($ field => $ username, 'password' => $ password)))


By default Auth :: attempt () requires (normally) 2 input-tan namely username and password. We only need to create a flexible username field.

filter_var ($ username, FILTER_VALIDATE_EMAIL)? 'email': 'username';
with the method above the username field we have created dynamically and automatically checks whether the input is an email or not.



So, this time. Happy coding !!!

Share this


0 Comments