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