0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel10でCSRFトークンミスマッチが起きた時にログイン画面にリダイレクトさせる方法

Last updated at Posted at 2023-08-31

Laravel5系で開発していた際は、renderメソッドに書く形でCSRFトークンミスマッチ時にリダイレクトさせていましたが、
Laravel10系では、registerメソッドに書くのが正解のようです。

app\Exceptions\Handler.php
<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

use Illuminate\Http\Request; // ★追加
use Illuminate\Session\TokenMismatchException; // ★追加

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        // ★ここから追加
        $this->renderable(function (\Exception $e, $request) {
            // 419エラー: CSRFトークンミスマッチエラーの場合の処理
            if ($e->getPrevious() instanceof TokenMismatchException) {
                return redirect()->route('auth.login')->withErrors([
                    'errors' => trans('auth.csrf_token_mismatched')
                ]);
            };
        });
    }
}
resources/lang/ja/auth.php
<?php

return [
    'csrf_token_mismatched' => 'CSRFトークンが一致しません。もう一度お試しください',
];

Viewでは以下のようなループ処理でエラーメッセージを取り出せます

resouces/views/auth/login.blade.php
@if ($errors->any())
      <div id="alert-messages" class="alert alert-danger">
        <ul>
    @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
    @endforeach
        </ul>
      </div>
@endif

参考URL

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?