Custom Login with Laravel Breeze authentication system

 Laravel provides some fantastic authentication systems to make programmer's life easier. Breeze is one of those. Today we will see how we can make a custom login system with Laravel Breeze.

 


Step 1: Make a route with Guest middleware

The very first thing is making a login route. You will have a default middleware, “guest” after installing the Breeze package. Use this with the route

Route::post('/login', [TestController::class,'Login'])->middleware('guest');

 

Step 2: Make the custom login function

Now we have to make a custom login function in the login controller. This function definition is written according to the Laravel breeze rules and properties.

function CLogin(LoginRequest $request){
    $credentialWrong = $request->authenticate();
    $request->session()->regenerate();
    if(!$credentialWrong){
        return true;
    }
    else{return $credentialWrong;}
}

 

Step 3: Customize the LoginRequest class

We are close to the end of the method. Now we need to customize the LoginRequest.php class. This class you will have on App>Http>Request>Auth ! There you need to customize many methods one by one. All we are going to explain is below.

*authenticate() method

public function authenticate()
{    
$blocking_time = $this->ensureIsNotRateLimited();     if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {         $wrong_rate = RateLimiter::hit($this->throttleKey());         return response()->json([             "blocking_time"=>$blocking_time,             "wrong_rate"=>$wrong_rate         ]);     }     RateLimiter::clear($this->throttleKey()); }

 

*ensureIsNotRateLimited()

public function ensureIsNotRateLimited()
{    
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {         return;     }     event(new Lockout($this));     $seconds = RateLimiter::availableIn($this->throttleKey());     return $seconds; }

 

Done!!

 

Now you can login by using the “/login” route. No need to generate any extra cookies or credentials. Rather it can detect the own user!

Post a Comment

Previous Post Next Post