Blog スタッフブログ

Laravel システム開発

[Laravel]csrfエラーの取得

システム開発担当のTFです。

やり方

  • ExceptionHandler を継承している、app\Exceptions\Handler.php を利用する
  • register 関数に、reportable で報告系の、 renderable で描画系の処理を登録できる
  • csrfトークンのエラーなので、TokenMismatchException の時処理を行う

サンプル

<?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
{
    // 省略
	
    public function register(): void
    {
		// 報告系の処理
        $this->reportable(function (Throwable $e) {
            //
        });
		
		// 描画系の処理
		$this->renderable(function (\Exception $e, $request) {
			// csrfエラー
			if($e->getPrevious() instanceof TokenMismatchException){
				// ログインに戻す
				return redirect()->route('login');
			}
		});
    }
}