Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

harsiese's avatar

Session flush when CSRF Token Exception

Hi, I hope that can help me and sorry for my English, I have my exception Handler in this way:

public function render($request, Exception $exception) {
        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
            if($request->ajax()) {
        session()->flush(); // Not working... I tried $request->session()->flush() also
        echo json_enconde(['errno'=>999]);  
            } else {
                return redirect()->action('ClientController@index');
            }
        }
        return parent::render($request, $exception);
    }

In the client I have a JS that reload the page when received errno === 999 for handle the ajax request, is reloading, but is entering in a loop because the session still exists when I debug my ClientController@index. ClientController@index

public function index() {
        if(session()->get('uuid')) { // This session is still valid after session()->flush()
            return view('conference.index');
        } else {
            return view('authentication.index');
        }
    }

I appreciate your help.

0 likes
1 reply
Snapey's avatar

i'm not sure what you are checking, but bear in mind that you will always have a session. If the previous one has expired, the framework will just start a new session.

Please or to participate in this conversation.