Laravel: Integrating Throttle in Custom Login

JaneTho picture JaneTho · Jul 19, 2017 · Viewed 11.9k times · Source

How to integrate laravel throttle if I did not use the default LoginController given by laravel?

here's my controller:

  use AuthenticatesUsers;

  //function for login
  public function login(Request $requests){
    $username = $requests->username;
    $password = $requests->password;

    /**to login using email or username**/
    if(filter_var($username, FILTER_VALIDATE_EMAIL)) {

      Auth::attempt(['email' => $username, 'password' => $password]);
    } else {

      Auth::attempt(['username' => $username, 'password' => $password]);
    }


    if(Auth::check()){
      if(Auth::user()->type_user == 0){

        return view('users.dashboard');

      }
      else{
        return view('admin.dashboard');
      }
    }
    else{

      return Redirect::back()->withInput()->withErrors(['message'=>$login_error],'login');

    }
  }

I want to limit the failed logins but I can't seem to make it work using my own controller. Can you guys help me please?

Answer

w1n78 picture w1n78 · Nov 2, 2017

add the following code inside your method. make it the first thing

// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
    $this->fireLockoutEvent($request);
    return $this->sendLockoutResponse($request);
}

now add the following code where log in fails. this will increment the failed attempt count.

$this->incrementLoginAttempts($request);

on successful login, add the following code so it resets.

$this->clearLoginAttempts($request);