Login only if user is active using Laravel Login only if user is active using Laravel laravel laravel

Login only if user is active using Laravel


Laravel 5.4 / 5.5

Override the default login() function by placing this function in your LoginController:

public function login(\Illuminate\Http\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);    }    // This section is the only change    if ($this->guard()->validate($this->credentials($request))) {        $user = $this->guard()->getLastAttempted();        // Make sure the user is active        if ($user->active && $this->attemptLogin($request)) {            // Send the normal successful login response            return $this->sendLoginResponse($request);        } else {            // Increment the failed login attempts and redirect back to the            // login form with an error message.            $this->incrementLoginAttempts($request);            return redirect()                ->back()                ->withInput($request->only($this->username(), 'remember'))                ->withErrors(['active' => 'You must be active to login.']);        }    }    // 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);}

Overriding the login() method in this way is recommended over many of the other answers on this question because it allows you to still use many of the more advanced authentication functionality of Laravel 5.4+ such as login throttling, multiple authentication guard drivers/providers, etc. while still allowing you to set a custom error message.


Laravel 5.3

Change or override your postLogin() function in your AuthController to look like this:

public function postLogin(Request $request){    $this->validate($request, [        'email' => 'required|email', 'password' => 'required',    ]);    $credentials = $this->getCredentials($request);    // This section is the only change    if (Auth::validate($credentials)) {        $user = Auth::getLastAttempted();        if ($user->active) {            Auth::login($user, $request->has('remember'));            return redirect()->intended($this->redirectPath());        } else {            return redirect($this->loginPath()) // Change this to redirect elsewhere                ->withInput($request->only('email', 'remember'))                ->withErrors([                    'active' => 'You must be active to login.'                ]);        }    }    return redirect($this->loginPath())        ->withInput($request->only('email', 'remember'))        ->withErrors([            'email' => $this->getFailedLoginMessage(),        ]);}

This code redirects back to the login page with an error message about the user being inactive. If you want to redirect to an authentication page you would change the line I marked with the comment Change this to redirect elsewhere.


In Laravel 5.4 open Auth/LoginController.php

and add this function:

/**     * Get the needed authorization credentials from the request.     *     * @param  \Illuminate\Http\Request  $request     * @return array     */    protected function credentials(\Illuminate\Http\Request $request)    {        //return $request->only($this->username(), 'password');        return ['email' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];    }

And you are done..!


Paste the following method to your LoginController.

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

The last two comma-separated parameters (active,1) act as a WHERE clause (WHERE active = '1') and can be alternatively written this way:

protected function validateLogin(Request $request){    $this->validate($request, [        $this->username() => Rule::exists('users')->where(function ($query) {            $query->where('active', 1);        }),        'password' => 'required|string'    ]);}

Normally, the validation method only checks if email and password fields are filled out. With the modification above we require that a given email address is found in a DB row with active value set to 1.

You can also customize the message:

protected function validateLogin(Request $request){    $this->validate($request, [        $this->username() => 'exists:users,' . $this->username() . ',active,1',        'password' => 'required|string',    ], [        $this->username() . '.exists' => 'The selected email is invalid or the account has been disabled.'    ]);}

Note that the above message will be shown both when a given email address doesn't exist or when the account is disabled.