Friday, March 4, 2022

[FIXED] Limit login attempts in Laravel 5.7

Issue

I have Laravel 5.7 project with custom login. How can I let Laravel accept three login attempts after that redirect for page waiting to 2 or 3 min, etc?

public function loginPost(LoginRequest $request)
{
    if (Auth::attempt(array('user_name' => $request->user_name, 'password' => $request->user_pass)))
    {
        if(Auth::check())
            return redirect('/');
        else
            return back();
    }
    else
    {
        return "login faled call administrator";
    }
}

Solution

u can do by two way

  1. add laravel bulit in throttle middleware in route for example

    Route::post("/user/login","LoginController@login")->middleware("throttle:10,2");
    

it will send 10 request per 2 minute

2.Use Built in Trait ThrottlesLogins

first of add ThrottlesLogins trait in loginController and this line in login method

if ($this->hasTooManyLoginAttempts($request)) {
    $this->fireLockoutEvent($request);
    return $this->sendLockoutResponse($request);
}

if(attempt()) {
    $this->clearLoginAttempts($request);
}else {
  $this->incrementLoginAttempts($request);
}

if attempt successfully then add this line in attempt method

$this->clearLoginAttempts($request);

else fail login then add this line in else condition

$this->incrementLoginAttempts($request);



Answered By - Jignesh Joisar

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.