I’m working on a Laravel 11 project and have a cookie that is excluded from being encrypted in the EncryptCookies middleware. Here’s how I set it in my middleware:
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
'pattr',
];
}
In my unit test, I set the cookie like this:
public function test_repeat_guest_can_store_an_attribution(): void
{
$pattr = uniqid();
$response = $this->withCookie('pattr', $pattr)
->withoutExceptionHandling()
->post('api/attributions', [
'utm_source' => 'Facebook',
]);
}
However, when I dd the value of the cookie in my controller, it’s still showing up as encrypted:
$cookie_id = uniqid();
if ($request->hasCookie('pattr')) {
$cookie_id = $request->cookie('pattr');
dd($cookie_id);
}
The output I get looks like this (encrypted cookie):
"EXAMPLE6Im1sRFdhSHdMdGhCZkFUU01pY0FMSUE9PSIsInZEXAMPLEjoiQlhkWENUWW1lZ25Vckt1QnhEWWZXTjN6TzRIS011EXAMPLEMTk9RR3ZjaTRDdVNFTEXAMPLEad0toVEcrdzhDQkpHd3Q2cmE0Rk9jZ0tMQWcvdXg0d1E9PSIsIm1hYyI6IjY5ZTFmMmEyNTYwNDczNEXAMPLEkYTA3OGFlODI0ZTkxZDU5YmRiNjQ2ZjVjMTRjMWJkMGZkN2MxYjQzOTEzOTMiLCJ0YWcEXAMPLE=="
I expected the cookie to remain unencrypted since I added it to the $except array in the EncryptCookies middleware. I also tried disabling the middleware in my test with withoutMiddleware() but the issue persists.
Why is the cookie still being encrypted in my unit test, and how can I fix it so that the cookie remains unencrypted?
2
Answers
Try to use this syntax instead, I can’t explain why but there is some funny behaviour with cookies in Laravel testing
I can’t set it directly on the "EncryptCookies" because this file is from the Laravel Framework core, so the custom code is lost when the composer update is run.
I had success setting the cookie so it is not encrypted on the "AppServiceProvider" using the "EncryptCookies" there.