The page has expired due to inactivity

Recently an a few of my projects I came across "The page has expired due to inactivity. please refresh and try again" . It was driving me up the wall.

The issue is when you use the @csrf on a form and it is inactive for sometime, which means the CSRF Token expires and throws this error.

Being an error, we are able to catch this and do something with it by editing the app/Exceptions/Handler.php file.

So thats all we need to do is write some code to tell Laravel what to do.

Open your app/Exceptions/Handler.php file, and use/modify this code.

public function render($request, Exception $e)

        if ($e instanceof \Illuminate\Session\TokenMismatchException)
            return redirect()
                        'status' => 'Oops! Your Validation Token has expired. Please try again',
                        'alert' => 'danger']);

        return parent::render($request, $e);

What we are telling the Handler.php file is that if the error is a TokenMismatchExeption, then redirect back with an error.

Note: If you are using to build your forms then you may get an error when using redirect()->back(), as it may not refresh the token, but by using just regular html tag in the template then it should be fine.

To learn more on error handling then visit Laravels Docs on Error handling