Set Request Cookie in Laravel Unit Test
In this article
To set a request cookie in a Laravel unit test, you use the withCookie() method on the test request builder, which attaches a cookie to the outgoing HTTP request before it hits your routes or controllers. This lets you simulate authenticated sessions, user preferences, or any cookie-dependent logic without manually manipulating the HTTP layer.
What You'll Need
- A Laravel application (version 5.5 or later, though the method has existed since early versions).
- PHPUnit installed and configured (comes by default with Laravel).
- Basic familiarity with Laravel's feature tests (tests extending
TestCase).
Step-by-Step
- Create a test file (if not already present) by running
php artisan make:test ExampleCookieTestfrom your project root. This creates a test intests/Feature. - Open the test file and ensure it extends
Tests\TestCase(the default). Add theRefreshDatabasetrait only if your test hits the database; otherwise, leave it out. - Write a test method that makes an HTTP request. For example:
public function test_cookie_is_sent(). - Use
withCookie()on the request builder. The method accepts two arguments: the cookie name and its value. Example:$response = $this->withCookie('theme', 'dark')->get('/settings'); - Chain multiple cookies if needed by calling
withCookie()multiple times before the HTTP verb:$this->withCookie('one', '1')->withCookie('two', '2')->get('/'); - Assert the response as usual. For example, check that the cookie value appears in the response body:
$response->assertSee('dark');or check a redirect:$response->assertRedirect('/login'); - Run the test with
php artisan testorvendor/bin/phpunitfrom the command line.
If you need to set a cookie that expires or has other attributes, you can pass a Symfony\Component\HttpFoundation\Cookie instance as the second argument instead of a plain value. Example: $cookie = new Cookie('name', 'value', now()->addDay()); then $this->withCookie($cookie)->get('/');
Common Mistakes
- Forgetting to call
withCookie()before the HTTP verb. The method is chained on the test instance, not the response. Calling$this->get('/')->withCookie()will fail. - Using
withCookie()on a non-existent route. The cookie is attached regardless, but if the route doesn't read it, your test may pass for the wrong reason. - Mixing up
withCookie()andwithUnencryptedCookie(). Laravel encrypts cookies by default. If you set a cookie withwithCookie(), it will be encrypted when the request is made. If your middleware expects a raw value (e.g., you usedwithUnencryptedCookie()in production), the test will fail. - Not clearing cookies between tests. Laravel's test framework resets state between tests, but if you manually set cookies in a
setUp()method, they persist across tests in the same class. Reset them intearDown()if needed.
Tips
- Use
withUnencryptedCookie()if you need to bypass encryption for testing purposes, especially when your middleware expects raw values (e.g., for signed cookies). - For session-based authentication, consider using
actingAs()instead of manually setting session cookies. It's cleaner and more reliable. - If you need to test cookie encryption/decryption, stick with
withCookie()and let Laravel handle the encryption. - Combine multiple cookies in a single request by chaining
withCookie()calls. This keeps the test readable. - Use named routes in your tests to avoid hardcoding URLs, making the test more robust to route changes.
Troubleshooting
- Cookie not appearing in the request: Double-check that you're calling
withCookie()before the HTTP verb. Also ensure you're using the correct method name (it'swithCookie, singular). - Encryption errors: If you get an error about decryption, your middleware might be trying to decrypt a cookie that wasn't encrypted. Use
withUnencryptedCookie()to send a raw value, or ensure your middleware uses theEncryptCookiesmiddleware properly. - Test passes but cookie isn't used: Verify that your route or controller actually reads the cookie. Add a debug line like
dump($request->cookie('name'));in your controller to see what's received. - Cookie value is null: This often happens when the cookie name doesn't match. Check for typos and remember that cookie names are case-sensitive.
- Session not persisting: If you're trying to set a session cookie, use
withSession()instead.withCookie()only sets a regular cookie, not the session ID.
Frequently Asked Questions
Can I set multiple cookies in one request?
Yes, chain multiple withCookie() calls before the HTTP verb, or pass an array of cookies to withCookies() (available in Laravel 5.8+).
How do I set a cookie with an expiration date?
Pass a Symfony\Component\HttpFoundation\Cookie instance as the second argument to withCookie(). You can set the expiry via the constructor.
What's the difference between withCookie() and withUnencryptedCookie()?
withCookie() encrypts the cookie value before sending, as Laravel does by default. withUnencryptedCookie() sends the raw value without encryption, which is useful for testing middleware that expects plain cookies.
Can I set a cookie for a JSON API test?
Yes, the same methods work for JSON requests. Just call withCookie() before postJson(), getJson(), etc.
Does withCookie() work with CSRF protection?
CSRF protection applies to POST requests and uses a token in the request body, not the cookie. The cookie is sent separately, so CSRF is unaffected. If you need to disable CSRF for testing, use the WithoutMiddleware trait.
Why is my cookie not encrypted when I use withUnencryptedCookie()?
That's the intended behavior. The method sends the value as-is, bypassing the encryption layer. Use it only when you're certain the middleware expects a raw value.