store, retrieve and delete cookie in laravel application

In this blog, we will show you how to Save Retrieve and Delete Cookies Data in Laravel. You will learn how to set, get, and delete cookies in a Laravel application with practical examples. This tutorial also explains how to forget cookies effectively in Laravel.

Here, we have also seen a few cookie functions like checking whether a cookie exists or more.

What are Cookies?

Web applications use cookies, small data files stored in the user’s browser, to track and identify returning users.

Websites use cookies to analyze user behavior and provide a better user experience.

In Laravel, we can perform cookie-related operations using a facade or request instance. For this example, we will use Facade.

Set Cookies in Laravel

We can use the Cookies::make() method to create or set cookies in Laravel.

$cookie =   Cookie::queue(Cookie::make('name', 'value', $minutes));

It will add cookie data to the queue and while creating cookies we have passed three parameters. The first one is the name of the cookie, the second is the value and third one is expire time in minutes.

We can also use the Cookies::forever() method to store cookies. The forever method will store cookies without expiry. So we can use it till the cookies data is not cleared by us or the user.

$cookie =   Cookie::forever('name', 'value');

Get or Retrieve Cookies

The Cookie::get() method is used to retrieve cookie information. We can get specific values from cookies by passing the key with the get method.

$data = Cookie::get('key');

We can also retrieve all cookies data by using the get method like the below:

$data = Cookie::get();

Delete or Remove Cookies

The Cookie::forget() method is used to remove the cookie’s information.

Cookie::forget('key');

Check If Cookie Exists

Sometimes we need to check if specific keys exist in cookies before performing other actions, and for this, we can use the Cookie::has() method.

Cookie::has('key');

The Cookie::has() method returns a boolean and is usually used within if conditions.

Conclusion

Here, We have taken short examples for storing, retrieving, or deleting cookies in the Laravel application.

For managing user session data efficiently, you can check out our blog Store, Retrieve, and Delete Data From Session In Laravel. This guide explains how to handle session data in Laravel, including storing, retrieving, and deleting information for a smooth user experience.