Modify existing Authorization module (email to username)

后端 未结 5 1627
灰色年华
灰色年华 2020-11-29 09:38

I would like to modify the existing Authorization module provided by Laravel 5, instead of asking for the email it will ask for the username field

相关标签:
5条回答
  • 2020-11-29 10:12

    Laravel search the variable $username in the file :

    Illuminate\Foundation\Auth\AuthenticatesUsers

    public function loginUsername() {
        return property_exists($this, 'username') ? $this->username : 'email';
    }
    

    As you can see, by default it will be named as 'email'.

    However you can override it in your AuthController by adding :

    protected $username = 'username';
    
    0 讨论(0)
  • 2020-11-29 10:12

    You do not need to modify the Auth module to do this, simply pass the user's identifier in the attempt. Use the field name in the attempt array as such:

    if (Auth::attempt(['username' => $username, 'password' => $password]))
        {
            return redirect()->intended('dashboard');
        }
    
    0 讨论(0)
  • 2020-11-29 10:12

    You can try to check the file Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers just to get the idea.

    Then add an override of postLogin on your AuthController:

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
        ]);
    
        $credentials = $request->only('username', 'password');
    
        if ($this->auth->attempt($credentials, $request->has('remember')))
        {
            return redirect()->intended($this->redirectPath());
        }
    
        return redirect($this->loginPath())
                    ->withInput($request->only('username', 'remember'))
                    ->withErrors([
                        'username' => 'These credentials do not match our records.',
                    ]);
    }
    

    You also need to add use Illuminate\Http\Request; to your AuthController.

    0 讨论(0)
  • 2020-11-29 10:18

    in controllers\auth\logincontroller add this

     protected $username = 'user_name';//user_name field name
    

    then go to Illuminate\Foundation\Auth\AuthenticatesUsers and change

     public function username()
        {
             return 'email';//change this with "return $this->username;"
        }
    

    with this method You can have different log in type in different controller for example in another controller controllers\admin_auth\logincontroller

    protected $username = 'phone_number';
    
    0 讨论(0)
  • 2020-11-29 10:20

    you can just override auth username function from LoginController.php in laravel 5.3

    public function username(){ 
       return 'username';
    }
    
    0 讨论(0)
提交回复
热议问题