質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

Q&A

2回答

4155閲覧

【Laravel5.7】特別なユーザ判定処理とエラー表示処理について

tajihiro

総合スコア14

Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

0グッド

0クリップ

投稿2019/02/10 15:33

編集2019/02/10 15:36

Laravelの FormRequest での入力値のバリデーションの仕組みは理解できました。
ここへ来て、Controller内において、DBからの値を取得したログイン判定処理で悩んでおります。
ちなみに、Laravel独自の認証は使用しません。

具体的には、$login_id と $password のパラメータを取得してユーザ判定を行いますが、その中で、該当ユーザのログイン条件を、ユーザテーブル以外の他の全く関係ないDBテーブルから条件取得する必要があります。

その場合の処理の組み立て方がよくわかりません。

質問としては、Controller からDBアクセスして、失敗した(Falseを返した)場合に、どのように元のログイン画面へ戻り(redirect)、エラーメッセージを出力すれば良いのかを悩んでおります。

  1. controller内にて
  2. ユーザ判定を行って
  3. 失敗した場合にログイン画面へ戻って
  4. 失敗した原因をエラー表示したい

php

1 public function auth(Request $request){ 2 //パラメータ取得 3 $email = $request->email; 4 $passwd = $request->passwd; 5 6 //ユーザ判定処理 (例) 7 $user = $this::isUser($email, $passwd); 8 $ok1 = $this::isValid1($user); 9 $ok2 = $this::isValid2($user); 10 $ok3 = $this::isValid3($user); 11 12 // *** この後の処理を場合をどうしようかと?**** 13 // if($okでない場合){ 14 //$rules = []; 15 //$messages = []; 16 //$validator = Validator::make([], $rules, $messages); 17 18 // *** 下記のようにログイン画面へ戻ってエラーメッセージを表示できないか? **** 19 if($validator->fails()){ 20 //ログイン失敗 21 return redirect('/login') 22 ->withErrors($validator) 23 ->withInput(); 24 }else{ 25 //ログイン成功 26 return redirect('/mypage'); 27 } 28 }

それとも、ユーザ判定でのエラーは、普通のvalidationとは切り離して考えた方が良いのでしょうか?
何かアドバイスが頂ければと思っています。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

Laravelの提供しているログイン処理を参考にするのがいいでしょう。ログイン画面でユーザ名とパスワードを入力してログインボタンを押したときに実行されるコントローラはApp\Http\Controllers\Auth\LoginController@loginです。このメソッドの実体は\Illuminate\Foundation\Auth\AuthenticatesUsers::loginです。

php

1 /** 2 * Handle a login request to the application. 3 * 4 * @param \Illuminate\Http\Request $request 5 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse 6 * 7 * @throws \Illuminate\Validation\ValidationException 8 */ 9 public function login(Request $request) 10 { 11 $this->validateLogin($request); 12 13 // If the class is using the ThrottlesLogins trait, we can automatically throttle 14 // the login attempts for this application. We'll key this by the username and 15 // the IP address of the client making these requests into this application. 16 if ($this->hasTooManyLoginAttempts($request)) { 17 $this->fireLockoutEvent($request); 18 19 return $this->sendLockoutResponse($request); 20 } 21 22 if ($this->attemptLogin($request)) { 23 return $this->sendLoginResponse($request); 24 } 25 26 // If the login attempt was unsuccessful we will increment the number of attempts 27 // to login and redirect the user back to the login form. Of course, when this 28 // user surpasses their maximum number of attempts they will get locked out. 29 $this->incrementLoginAttempts($request); 30 31 return $this->sendFailedLoginResponse($request); 32 }

ログインに失敗したときは最後の行のreturn $this->sendFailedLoginResponse($request);が実行されます。

さて、sendFailedLoginResponse

php

1 /** 2 * Get the failed login response instance. 3 * 4 * @param \Illuminate\Http\Request $request 5 * @return \Symfony\Component\HttpFoundation\Response 6 * 7 * @throws \Illuminate\Validation\ValidationException 8 */ 9 protected function sendFailedLoginResponse(Request $request) 10 { 11 throw ValidationException::withMessages([ 12 $this->username() => [trans('auth.failed')], 13 ]); 14 }

となっており、単にバリデーションエラーのときと同じ例外を投げているだけです。Laravelのデフォルトの例外ハンドラはValidationExceptionのときにはエラーと入力の内容をひきついで元の画面にリダイレクトするのでこの場合は元のログインフォームの画面になります。

他にも色々参考になるのでAuthenticatesUsersトレイトは一度ざっと読んでみることをおすすめします。

投稿2019/02/11 02:47

crhg

総合スコア1175

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tajihiro

2019/02/11 03:52

ありがとうございます。 エラー時に、元のログイン画面で、それぞれ(isValid1/isValid2/isValid3)のエラーの内容表示ができればと思っております。 読み解く必要がありそうですね。
guest

0

Laravel自体が使っているやり方はこれなんですが、これは使えるんでしょうか?

php

1// 上に 2use Illuminate\Auth\AuthenticationException; 3 4// 失敗した際に 5throw new AuthenticationException('失敗の理由')

こうしたら、App\Exceptions\Handlerの親クラスにあるメソッドunauthenticated()にハンドルされます。

php

1protected function unauthenticated($request, AuthenticationException $exception) 2{ 3 return $request->expectsJson() 4 ? response()->json(['message' => $exception->getMessage()], 401) 5 : redirect()->guest($exception->redirectTo() ?? route('login')); 6}

投稿2019/02/11 01:50

Bremenkanp

総合スコア205

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tajihiro

2019/02/11 03:54

ありがとうございます。 エラー時に、元のログイン画面で、それぞれ(isValid1/isValid2/isValid3)のエラーの内容表示ができればと思っております。 redirect先への、エラー内容の受け渡しを考えてみます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問