Login only if user is active using Laravel

前端 未结 19 1859
孤城傲影
孤城傲影 2020-11-30 23:26

I\'m currently working on my Laravel app and to prevent spam I decided that only active users are able to login. I\'m currently using Laravel\'s login system just like in La

19条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 23:48

    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.

提交回复
热议问题