raj asked this 4 years ago

Laravel session expired: Properly handle TokenMismatchException

Hi,

I am getting "Whoops, looks like something went wrong" page when session expired. I want to redirect user to login page instead of showing this error message. I am using Laravel 5.3. I think i need to catch the TokenMismatchException and handle it properly?


ben100 4 years ago
2 likes

This is how I am doing it:

Edit app\Exceptions\Handler.php

Add TokenMismatchException to the top:

use Illuminate\Session\TokenMismatchException;


Then create a custom exception render in your render() method for the Handler class

 /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $ex)
    {
    	if ($ex instanceof TokenMismatchException) {

            return redirect(route('loginpage'))->with('message', 'Your session expired');
    	}
        return parent::render($request, $ex);
    }
Guest 3 months ago

Not working for laravel 8


Method 'App\Exceptions\Handler::render()' is not compatible with method 'Illuminate\Foundation\Exceptions\Handler::render()'.intelephense(1038)