Skip to content

Instantly share code, notes, and snippets.

@fernandohs1500
Created April 26, 2022 14:24
Show Gist options
  • Save fernandohs1500/0db758200d83fb81c24e38355d5ae7ee to your computer and use it in GitHub Desktop.
Save fernandohs1500/0db758200d83fb81c24e38355d5ae7ee to your computer and use it in GitHub Desktop.
handling the error CSRF token mismatch in Laravel.
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class VerifyCsrfToken extends Middleware
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
public function handle($request, Closure $next)
{
if ($request->route()->getActionMethod() == 'login') {
$this->except[] = route('brackets/admin-auth::admin/login');
}
if ($request->route()->named('brackets/admin-auth::admin/logout')) {
//Deletando o coockie
unset($_COOKIE['XSRF-TOKEN']);
unset($_COOKIE['myapp_session']);
setcookie("XSRF-TOKEN", "", time() - 3600,"/");
setcookie("myapp_session", "", time() - 3600,"/");
if (!Auth::check() || Auth::guard()->viaRemember()) {
$this->except[] = route('brackets/admin-auth::admin/logout');
}
}
return parent::handle($request, $next);
}
}
@fernandohs1500
Copy link
Author

After many unsuccessful attempts, I decided to go deeper and solve the problem at the root.

app/Http/Middleware/VerifyCsrfToken.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment