Laravel Framework | PHP & MySQL | Tutorials

David Carr

Laravel add login throttling with custom login controller

When using a custom login controller by default it won't have the login throttling applied.

Login throttling will stop a user attempting to login repeatedly after a set number of login attempts has been made. When locked out no login's will be allowed until a set amount of time has passed.

To add this create a hasTooManyLoginAttempts method to your controller, inside the method set the number of login attempts allowed and the number of minutes a lockout will last for, in this example, 5 attempts are allowed if exceeded a lockout will happen for 10 minutes.

/**
 * Determine if the user has too many failed login attempts.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function hasTooManyLoginAttempts(Request $request)
{
    $attempts = 5;
    $lockoutMinites = 10;
    return $this->limiter()->tooManyAttempts(
        $this->throttleKey($request), $attempts, $lockoutMinites
    );
}

This method will get used as long as your login method called it like this:

public function login(Request $request)
{
    $this->validateLogin($request);

    // 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);
    }

    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);

    return $this->sendFailedLoginResponse($request);
}

 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.