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 file, 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 Cookies::make() method to create or set cookies in Laravel.
It will add cookie data to the queue and while creating cookies we have passed three-parameter. The first one is name of cookie, second is value and third one is expire time in minutes.
We can also use 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 user.
Get or Retrieve Cookies
The Cookie::get() method is used to retrieve cookie information. We can get specific values from cookies by passing key with get method.
We can also retrieve all cookies data by using get method like below:
Delete or Remove Cookies
The Cookie::forget() method is used to remove the cookie's information.
Check If Cookie Exists
Sometimes we require to check specific key exists in cookies before performing any other actions then we can use Cookie::has() method.
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.