Search code examples
phplaravelcookies

Laravel Test Cookie is Encrypted Despite Being Excluded from EncryptCookies Middleware


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?


Solution

  • Try to use this syntax instead, I can't explain why but there is some funny behaviour with cookies in Laravel testing

    $cookies = ['name' => 'value']; 
    $response = $this->call('POST', '/route', [], $cookies);