laravel-5.7

How to get the number of login attempts in Laravel?


Laravel version 5.7 -

I am currently attempting to grab the number of login attempts. The Laravel's documentation does not provide a guide for this. But I think I am getting closer to finding the answer on my own by backtracking all the methods being called.

Anyhow, my goal is to display the number of 'logins attempted / max login attempt' before the lockout.

In Auth\LoginController I can easily get the number of maxAttempts, and even set my preferred number of max attempts:

protected $maxAttempts = 3;

Great. So I create a function to get login attempt details:

public function getCurrentAttempts() {
    $limiter = $this->limiter();

    $login_attempts = array(
        // gets the number of current login attempted
        'currentAttempts' => $limiter->hit('user'),

        // get the number of max attempts allowed
        'maxAttempts' => $this->maxAttempts(),

        // return 1 or 0 if current login attempts reached max attempts
        'locked' => $this->limiter()->tooManyAttempts('user', $this->maxAttempts())
    );

    return view('auth.login')->withLoginAttempts(
        $login_attempts
    );
}

Please note:

$this->limiter()->hit(key) <<< expects a key. I really don't know what kind of key it is expecting. Help anyone? I typed 'user', and for some reason is sending me back the correct number of attempts. But is this correct? Is that the 'key' that $limiter->hit() is expecting? Doesn't the 'key' has something to do with Request?

Other things to note: Nicely enough, from the LoginController I can easily get the $maxAttempts value by simply $this->maxAttempts(), that's really nice. But what about the number of current login attempts? Wouldn't it be ideal to have it in the same place? That's what I am trying to get.


Solution

  • After reading the Laravel docs several times, I began to try various classes already built in within the framework that allowed me to achieve my goal (getting the current number of login attempts)

    In the LoginController we must use Illuminate\Http\Request; and then by method injection, the Request $request can be captured in the method.

    I was then able to get the 'throttleKey', which is the key that I needed like so: In the LoginController's method body, $this->limiter()->hit($this->throttleKey($request));