Laravel 5.8 showing "419 Page Expired" after clicking logout from an already cleared session

Well that's an obvious message you can maybe try to make a better layout for that page, but still it is good to show it so the user knows what happened. If you want to handle it differently you can try to redirect to the login page.

So in your app\Exceptions\Handler.php file within the render method add this:

if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
    return redirect()->route('login');
}

IMHO you can try to modify your app/Http/Middleware/VerifyCsrfToken.php file. Edit the the $except property with something like this:

class VerifyCsrfToken extends Middleware
{       
    protected $except = [
        'http://example.com/logout',
    ];

A solution to the problem is relatively simple, and requires a small addition to the VerifyCsrfToken middleware;

use Closure;


    public function handle($request, Closure $next)
    {
        if(!Auth::check() && $request->route()->named('logout')) {
        
            $this->except[] = route('logout');
            
        }
        
        return parent::handle($request, $next);
    }

Normally this file contains just an $except array of routes that should be ignored from csrf.

In this code we override the handle method and perform two checks.

  • is the user a guest (ie, not using an authenticated session), and,
  • is the route the logout route

If both are true then we add 'logout' to the except array. We then pass control to the core VerifyCsrfMiddleware which recognises the presence of the logout route in the array, and bypasses the check. The form data is correctly posted and we are redirected using the LogoutResponse.

The user sees no error page.

By checking in this way, we ensure that genuine logout requests are still protected by CSRF Token.