store, retrieve and delete cookie in laravel application

In this blog, we will show you how to set, get, and delete cookies in the Laravel application. We will take a few examples of cookies in Laravel. This tutorial will give how to forget cookies in Laravel.

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

What are Cookies?

Cookies are small data files, which is stored in the remote browser. And with the help of cookies tracking/identifying return users in web applications.

Generally, cookies are used 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 are required to check specific keys that exist in cookies before performing any other actions then we can use the Cookie::has() method.

Cookie::has('key');

The Cookie::has() method returns a boolean. It’s generally used with if conditions.

Conclusion

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