Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nikocraft's avatar

How to override auth login function in Laravel?

I need to override laravels default login function, however I am confused by the code I find there. I do not understand how laravel AuthenticatesUsers.php verifies that user exists in db and then authenticates the user.

I've come to this function in AuthenticatesUsers

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

I guess I would need to override this function inside auth/LoginController.php

but I do not understand how it works. Where are guard() and attempt() implemented, I guess the real action happens there. I need to add another condition to the login.

Anyone understands how laravels default login works? and those two functions guard() and attempt(), for example attempt is not implemented inside AuthenticatesUsers.php it self and I belive its this function I should really override.

Where can I find it's implementation?

0 likes
18 replies
BishoyWagih's avatar
Level 13

i think you don't need to re implement laravel auth, its just you need to understand it..

laravel uses attempt method to check user credentials like email , password

so in case, if you need to authenticate your user with phone and password..

just pass to attempt method array containing phone and password,

if you need to authenticate your user with email and password and only active users

just pass to attempt function email , password , active fields..

its so easy.. just read the documentation..

https://laravel.com/docs/5.6/authentication

3 likes
nikocraft's avatar

You are correct I want to check for is_activated. I did this for now:

I copied the whole login function into LoginController.php and this is the interesting part

        if ($this->guard()->validate($this->credentials($request))) {
            $user = $this->guard()->getLastAttempted();
            if ($user->is_activated && $this->attemptLogin($request)) {
                return $this->sendLoginResponse($request);
            } else {
                $this->incrementLoginAttempts($request);
                if ($request->ajax()) {
                    return response()->json([
                        'error' => 'This account is not activated.'
                    ], 401);
                }
            }
        }

If I do it as you suggest, how can I also generate the error message as above only if is_activated is false on that particular user?

2 likes
nikocraft's avatar

and how exactly do I tell attempt to also check the is_activated field

What would I put here inside attempt so it checks additional column for true or false?

        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
1 like
nikocraft's avatar

ok I see now, example is in the documentation. Thanks :)

1 like
nikocraft's avatar

yes it was very usefull :) thanks!

Btw if anyone in future wonders what I did, here is how I solved it

I still had to override the login function inside LoginController.php this had to be done so I get all the throttling and error messages that can be generated by the system. Here is my final function

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

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

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

        if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_activated' => 1])) {
            // return redirect()->intended('dashboard');
        }  else {
            $this->incrementLoginAttempts($request);
            return response()->json([
                'error' => 'This account is not activated.'
            ], 401);
        }

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

@BishoyWagih if you think it could have been even more simplified plz let me know :)

5 likes
nikocraft's avatar

Actually its good except we got another problem now.

If user credentials do not match what is found in the database now user will only get back "This account is not activated." error message, which may not be true since user can be activated but he typed wrong password. Any idea how to solve this problem? I have to show the user correct error message.

nikocraft's avatar

Ok this is final function if anyone from the future wonders what the solution was:

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

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

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

        if($this->guard()->validate($this->credentials($request))) {
            if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_activated' => 1])) {
                // return redirect()->intended('dashboard');
            }  else {
                $this->incrementLoginAttempts($request);
                return response()->json([
                    'error' => 'This account is not activated.'
                ], 401);
            }
        } else {
            // dd('ok');
            $this->incrementLoginAttempts($request);
            return response()->json([
                'error' => 'Credentials do not match our database.'
            ], 401);
        }
    }

this part validates the correct credentials but does not login the user:

 if($this->guard()->validate($this->credentials($request)))

this part logs-in the user if all requirments are met:

if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_activated' => 1])) 
2 likes
jlrdw's avatar

if anyone from the future wonders what the solution was:

Hi, from year 2099, thanks very helpful

6 likes
nikocraft's avatar

@jlrdw hi, how are things in the future, are Marty and Doc still around? Is everything ok with Earths gravity?

1 like
jlrdw's avatar

Funny, I couldn't resist the way you worded your reply about the future. Oh and the future all programming is done in the mind.

2 likes
snipesnipes's avatar

hey thx for this , yes it has helped me to build my login system , well im not that much in the future but 1 year later I guess I am.

2 likes
AlexSYS's avatar

Hi guys. I have some problem with auth. I have table Persons with columns (Person_Login, Person_Hash) and login.blade with fields Person_Login, password, but can't pass auth. My condition is

if(Auth::attempt(['Person_Login'=>$request->Person_Login, 'Person_Hash'=>$request->password]))

But it always false.

In documentation i find that i don't need to hash password field, but i can't understand how laravel know what field contains hash? I log queries to dabase and see that query is

select top 1 * from [Persons] where [Person_Login] = ? and [Person_Hash] = ?
array (
  0 => 'User',
  1 => 'Password',
)  

where is Hash of password?

When i registrate new user - everything is ok: creation and logging

ConorSeb20's avatar

would this be a valid option? $this->validate($request, [ 'email' => 'required|email', 'password' => 'required', ]);

    if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'status' => 0])) {
        return redirect($this->loginPath())
            ->withInput($request->only('email', 'remember'))
            ->withErrors('Your account is Inactive or not verified');
    }

I input the code for my login form at https://tophomeworkexpert.com/

1 like
AlexSYS's avatar

In LoginController:

protected function username()
    {
        return 'Person_Login';
    }

In AuthenticatesUsers:

 protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

validateLogin return true, but Auth::attempt return false

1 like
martinbean's avatar

@crackmixer If you have a question, create your own thread. Don’t bump a thread that last had activity nearly half a decade ago with a completely unrelated question.

Please or to participate in this conversation.