I am using Laravel 9.41.0 and PHP 8.1. When Laravel’s default session timeouts, accessing any protected routes after that throws this exception. Laravel is not redirecting to login route which I have already defined. The exception occurs in VerifyCsrfToken
middleware. Here is the method where exception occurs:
C:wamp-newwwwtwicterminal.comvendorlaravelframeworksrcIlluminateFoundationHttpMiddlewareVerifyCsrfToken
.php
: 191
/**
* Add the CSRF token to the response cookies.
*
* @param IlluminateHttpRequest $request
* @param SymfonyComponentHttpFoundationResponse $response
* @return SymfonyComponentHttpFoundationResponse
*/
protected function addCookieToResponse($request, $response)
{
$config = config('session');
if ($response instanceof Responsable) {
$response = $response->toResponse($request);
}
$response->headers->setCookie($this->newCookie($request, $config));
return $response;
}
This line in the method: $response->headers->setCookie($this->newCookie($request, $config));
is where the exception emerges from.
I googled this issue a lot but haven’t find any working solution yet. There are similar questions here on StackOverflow their scenarios, origin and use cases are different. Their solutions didn’t work for me either.
Note: This exception occurs only for default auth
middleware protected routes after default session timeouts.
2
Answers
Thank you everyone. I love the community and it's amazing helping each other.
I did extensive search and none of the solution worked for me. Luckily, I sorted out the problem by myself but forgot to add the answer here. Previously, I had changed the Laravel's default
Handler
class (for handling exceptions) and had added this method for an unauthenticated API request. It worked fine for API calls but web requests were having issues. Here is the method:What I forgot to add was this line at the end of the method and this was the reason why
$response
object was null. Now it works fine.PS:- Later I found a more elegant solution. Something that was the "Laravel's way" of doing stuff. I called the
renderable
method of the exception class inside register method ofHandler
class and caught theAuthenticationException
exception. Here is a look:For each class in your
app/Http/Middleware
folder, check eachhandle
method and make sure that each one always returns an instance ofIlluminateHttpResponse
. You said that you have no custom middleware and didn’t modify any of the middleware classes that Laravel gave you. Check them closely. Somewhere you are ending up with a null$response
variable that is supposed to be an instance ofIlluminateHttpResponse
. The most likely cause is ahandle
method not returning a value directly (thus returning null).