How to Create and Delete Cookies in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to create and delete cookies in Laravel.

 

How to create and delete cookies in Laravel

In Laravel, you can create and delete cookies using the Cookie facade provided by the framework. The Cookie facade provides a convenient way to work with cookies, and it abstracts away the details of setting and deleting cookies in the underlying PHP code.

To create a cookie, you can use the Cookie::queue() method, which adds a cookie to the response that will be sent back to the client:

// Set a cookie with the name "my_cookie" and the value "my_value"
Cookie::queue('my_cookie', 'my_value');

 

You can also set additional parameters for the cookie, such as the expiration time, the path, and the domain:

// Set a cookie with the name "my_cookie", the value "my_value", and an expiration time of 60 minutes
Cookie::queue('my_cookie', 'my_value', 60);

// Set a cookie with the name "my_cookie", the value "my_value", and a path of "/my/path"
Cookie::queue('my_cookie', 'my_value', 60, '/my/path');

// Set a cookie with the name "my_cookie", the value "my_value", and a domain of ".example.com"
Cookie::queue('my_cookie', 'my_value', 60, '/', '.example.com');

 

To delete a cookie, you can use the Cookie::forget() method, which adds a cookie to the response with an expiration time in the past, effectively deleting the cookie:

// Delete the cookie with the name "my_cookie"
Cookie::forget('my_cookie');

 

You can also set additional parameters for the cookie, such as the path and the domain, to ensure that the cookie is deleted correctly:

// Delete the cookie with the name "my_cookie" and a path of "/my/path"
Cookie::forget('my_cookie', '/my/path');

// Delete the cookie with the name "my_cookie" and a domain of ".example.com"
Cookie::forget('my_cookie', '/', '.example.com');

 

Note: When you create or delete a cookie using the Cookie facade, the cookie is added to or removed from the response that will be sent back to the client, so you should make sure that you call these methods before returning the response from your controller method.

Comments 0

Leave a comment