0
0

More than 3 years have passed since last update.

【Laravel】AuthenticatesUsersを用いたログインで認証失敗時のイベントをオーバライドして独自のメッセージをレスポンスする。

Posted at

メモとして残します。

AuthenticatesUsersを用いたログインで認証失敗時のイベント(sendFailedLoginResponse)
をオーバライドするして独自のメッセージを設定してレスポンスする方法をメモ。

■やり方

今回は下記のようにLockFlgを独自の認証ルールとして追加したとする。

credentialsをオーバーライド↓

LoginController.php
protected function credentials(Request $request)
{
    $conditions = $request->only($this->username(), 'password');
    $conditions_custom = array_merge(
        $conditions,
        ['LockFlg' => '0'] //ログイン条件追加:LockFlgが0であればログインできる。
    );
    return $conditions_custom;
}

sendFailedLoginResponseをオーバーライド↓

LoginController.php
// ログイン失敗時のレスポンス
protected function sendFailedLoginResponse(Request $request)
{
    $errors = [$this->username() => [trans('auth.failed')]]; //デフォルトエラーメッセージ

// ここから好きに条件見るなりで、$errorsに好きなエラー文を設定
    //ユーザ情報を取得して条件確認する。
    $user = \App\Models\User::where($this->username(), $request->{$this->username()})->first();
    if ($user && \Hash::check($request->password, $user->getAuthPassword()) && (string)$user->LockFlg=== '1') {
        $errors = [$this->username() => 'アカウントがロックされています。システム管理者にお問い合わせ下さい。'];
    }

    throw ValidationException::withMessages($errors);
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0