04 February 2019

How to Login use username Laravel 5.7

Hello guys, when I am stuck for logins Laravel does not use email but uses other fields, then I find a bright spot for the problem, I immediately document it to remember.

This is simple trick how to auth login use username or whatever on Laravel 5.7.
Before we start to use this trick, make sure you already have Laravel project installed.
run command:
 laravel new [your-app]  
Then, setting your key:generate use this comand:
php artisan key:generate
setting your .env file matching your database configuration. Lets get started guys.

Routing

Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

 php artisan make:auth  

This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points. A HomeController will also be generated to handle post-login requests to your application's dashboard.

Username Customization

By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController:

Just simple modify Controller\Auth\LoginController file like below:
 <?php  
 namespace App\Http\Controllers\Auth;  
 use App\Http\Controllers\Controller;  
 use Illuminate\Foundation\Auth\AuthenticatesUsers;  
 class LoginController extends Controller  
 {  
   /*  
   |--------------------------------------------------------------------------  
   | Login Controller  
   |--------------------------------------------------------------------------  
   |  
   | This controller handles authenticating users for the application and  
   | redirecting them to your home screen. The controller uses a trait  
   | to conveniently provide its functionality to your applications.  
   |  
   */  
   use AuthenticatesUsers;  
   /**  
    * Where to redirect users after login.  
    *  
    * @var string  
    */  
   protected $redirectTo = '/admin';  
   /**  
    * Create a new controller instance.  
    *  
    * @return void  
    */  
   public function __construct()  
   {  
     $this->middleware('guest')->except('logout');  
   }  
   // public function loginUsername()  
   // {  
   //   return 'name';  
   // }  
   public function username()  
   {  
     return 'name';  
   }  
 }  

Now, you can authenticate use username field on login page. If you want more information, you can follow this link to official documentation.  This is simple way to login use Username
Have a nice day

No comments: