Laravel Cookies


Working with Cookies in Laravel

Cookies are small files that store data on a user's computer, allowing you to maintain state across multiple requests. In Laravel, working with cookies is simple and integrated with the framework’s request and response system. You can easily create, retrieve, and delete cookies using Laravel's Cookie facade or helper methods.

Setting Cookies

To set cookies in Laravel, you use the Cookie facade or the global cookie() helper function. Cookies are sent to the browser in the HTTP response, and you can specify their expiration time, security settings, and more.

Example: Setting a Cookie

use Illuminate\Support\Facades\Cookie; public function setCookie(Request $request) { // Set a cookie with the name 'name', value 'John Doe', and a lifetime of 60 minutes Cookie::queue('name', 'John Doe', 60); // The cookie is automatically queued and will be sent with the response return response('Cookie has been set!'); }

In this example, Cookie::queue() is used to add the cookie to the response. The browser will receive the cookie in the HTTP headers, and it will be available for future requests.

You can also create a cookie instance using the cookie() helper function:

public function setCookie(Request $request) { // Create a cookie instance and attach it to the response $cookie = cookie('name', 'John Doe', 60); // Create a cookie for 60 minutes return response('Cookie has been set!')->cookie($cookie); }

Setting Additional Cookie Options

You can specify additional options when creating a cookie, such as:

  • Path: Specifies the path where the cookie is available.
  • Domain: Specifies the domain where the cookie is available.
  • Secure: Indicates if the cookie should only be sent over HTTPS.
  • HttpOnly: Indicates if the cookie should only be accessible through the HTTP protocol and not JavaScript.
  • SameSite: Prevents the browser from sending this cookie along with cross-site requests (can be lax, strict, or none).
// Create a cookie with additional options $cookie = cookie('name', 'John Doe', 60, '/', '.example.com', true, true, false, 'lax');

This creates a cookie with the following attributes:

  • Lifetime: 60 minutes
  • Path: / (cookie is available on all paths)
  • Domain: .example.com
  • Secure: True (only sent over HTTPS)
  • HttpOnly: True (cannot be accessed via JavaScript)
  • SameSite: lax

Retrieving Cookies

To retrieve the value of a cookie, you can use the Cookie facade or the cookie() helper. Cookies are automatically attached to the incoming HTTP request, and you can access them like this:

public function getCookie(Request $request) { // Retrieve the value of the 'name' cookie $value = $request->cookie('name'); return response('Cookie Value: ' . $value); }

In this example, the $request->cookie('name') method retrieves the value of the name cookie from the incoming request.

You can also use the Cookie facade to retrieve a cookie:

$value = Cookie::get('name');

Deleting Cookies

To delete a cookie, you can set its expiration time to a past time, which causes the browser to delete the cookie.

public function deleteCookie() { // Delete the 'name' cookie Cookie::queue(Cookie::forget('name')); return response('Cookie has been deleted!'); }

The Cookie::forget('name') method creates a cookie with an expiration time in the past, and Cookie::queue() queues it for deletion in the response.

Cookie Encryption

By default, Laravel automatically encrypts all cookies, ensuring that they are secure and tamper-resistant. You don’t need to manually encrypt or decrypt cookies, as Laravel handles this for you.

If you want to disable encryption for specific cookies, you can add the cookie name to the $except property in the EncryptCookies middleware:

class EncryptCookies extends Middleware { protected $except = [ 'cookie_name', // Specify cookies that should not be encrypted ]; }

Example: Complete Cookie Workflow

Here’s an example of setting, retrieving, and deleting a cookie in a controller:

use Illuminate\Http\Request; use Illuminate\Support\Facades\Cookie; class CookieController extends Controller { // Set a cookie public function setCookie() { Cookie::queue('user', 'John Doe', 60); // Set cookie for 60 minutes return response('Cookie set'); } // Get a cookie public function getCookie(Request $request) { $user = $request->cookie('user'); // Retrieve the 'user' cookie return response('User: ' . $user); } // Delete a cookie public function deleteCookie() { Cookie::queue(Cookie::forget('user')); // Delete the 'user' cookie return response('Cookie deleted'); } }
  • Setting a cookie: The setCookie() method stores a cookie named user with the value John Doe for 60 minutes.
  • Retrieving a cookie: The getCookie() method retrieves the value of the user cookie.
  • Deleting a cookie: The deleteCookie() method deletes the user cookie.

Using Cookies with Response Objects

Cookies are often attached to response objects in Laravel, meaning they are sent back to the client along with the HTTP response.

public function responseWithCookie() { // Create a cookie and return a response with it return response('Hello!')->cookie('user', 'John Doe', 60); }

In this example, the cookie is sent along with the HTTP response, allowing the client to store it for later use.