user6073700 user6073700 - 1 month ago 17
PHP Question

Add an extra condition for login in laravel 5.3

I am trying to authenticate a user with the obvious email and password and also if the ban_status is set to 0 in the database.

I have had a look at the newest laravel docs and I have tried it this way in the AuthenticateUsers.php

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


This does not do anything as far as I can tell and will log in the user regardless whether there ban status is 0 or not, where should I be doing this extra condition?

tam tam
Answer

To make a long story short, what you are actually trying to do in the code you posted is to check the ban_status value being passed in from the $request, or in other words the login form.

My understanding of your questions is that this is not really what you want.

Instead, try this:

Override the login method of AuthenticatesUsers by defining it in LoginController, with the following small addition to check for your ban_status:

public function login(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 ($lockedOut = $this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

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

    $credentials = $this->credentials($request);

    if ($this->guard()->attempt($credentials, $request->has('remember'))) {
        if ($this->guard()->user()->ban_status === 0) { // ADDED THIS CHECK
            return $this->sendLoginResponse($request);
        }
    }

    // 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.
    if (! $lockedOut) {
        $this->incrementLoginAttempts($request);
    }

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