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
$cookie = Cookie::queue(Cookie::make('name', 'value', $minutes));
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.
$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 key with get method.
$data = Cookie::get('key');
We can also retrieve all cookies data by using get method like below:
$data = Cookie::get();
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.
Here, We have taken short examples for storing, retrieving, or deleting cookies in the Laravel application.