validationlaravel-5authenticationextra

Extend laravel login validation


How would I extend the laravel login with extra validation rules. I would like to check if user has role on successfull login, if there is no role attached to user I want to deny the login process.

I see that in LoginController I can override the login method

public function login(\Illuminate\Http\Request $request)
{
    //dd($this->validateLogin($request));
    parent::login($request);
}

but I have no idea how do I get back the user object


Solution

  • If I understand it correctly, the user must authenticate itself and THEN you want to check the role. It is not required to have a specific role. If so, you can override the authenticated() method on your LoginController like this: ( You have to write use Illuminate\Http\Request; on top of the File.

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        if(empty($user->role)) {
            $this->guard()->logout();
            return back()->withErrors(['There is no role specified']);
        }
    }
    

    If you want the user to have s specific role you can override the credentials() method in the LoginController:

    protected function credentials(Request $request)
    {
        $credentials = $request->only($this->username(), 'password');
        $credentials['role'] = 'requiredRole';
        return $credentials;
    }