LoginSignup
0
0

More than 1 year has passed since last update.

Laravelのバリデーションエラー時にoldや$errorsが消える

Posted at

概要

LaravelのFormRequestでバリデーションを入れた。
バリデーションに引っ掛かると前のページに戻されるがフラッシュセッションがバグってoldも$errorsも空になる。

検証結果

バリデーションエラーを検知すると以下が発動。

laravel_project/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php

    protected function failedValidation(Validator $validator)
    {
        throw (new ValidationException($validator))
                    ->errorBag($this->errorBag)
                    ->redirectTo($this->getRedirectUrl());
    }

xdebugで追いかけていると、ここで一回セットされていた。
が、なぜかもう1周走って
1週目は sessionの _new が _old になり。
2週目で _old がクリアされていた。

laravel_project/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php

    protected function handleStatefulRequest(Request $request, $session, Closure $next)
    {
        // If a session driver has been configured, we will need to start the session here
        // so that the data is ready for an application. Note that the Laravel sessions
        // do not make use of PHP "native" sessions in any way since they are crappy.
        $request->setLaravelSession(
            $this->startSession($request, $session)
        );

        $this->collectGarbage($session);

        $response = $next($request);

        $this->storeCurrentUrl($request, $session);

        $this->addCookieToResponse($response, $session);

        // Again, if the session has been configured we will need to close out the session
        // so that the attributes may be persisted to some storage medium. We will also
        // add the session identifier cookie to the application response headers now.
        $this->saveSession($request);

        return $response;
    }

#原因

laravel_project/app/Http/Kernel.php

 \Illuminate\Session\Middleware\StartSession::class

を2回コールしていた。

たぶんデフォルトは以下の場所にしかなかったのではと思うが、

    protected $middlewareGroups = [
        'web' => [
          ..... 
        ],

過去のタスクで
以下の中にも書く修正を入れていた。

protected $middleware = [
   ...
]

結果としてweb.phpに入っているルートでは全部フラッシュセッションを2回処理していたらしい。

普通、この状態で長期間放置されることはありえないのですが、今回はweb.phpとadmin.phpにルートファイルが分かれていて、今までにフラッシュセッションを使っているのが管理画面だけだったため、気づくことがなかった。

他のパターン

Kernel.phpに以下の記述がない場合も表示されない。

\Illuminate\View\Middleware\ShareErrorsFromSession::class,

.envのセッションドライバー

セッションドライバーがクッキーだと動かないのでファイルにするようにとのこと。
データベースでも問題ないと思う。たぶん。

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