Cookie Creation

You can create a cookie by the use of Laravel’s global cookie helper. The global cookie helper is nothing but an instance of Symfony\Component\HttpFoundation\Cookie. A programmer can integrate a cookie with the response by the help of withCookie() method. Well, to call the withCookie() method, you need to create an instance for the response (IlluminatHttp\Response) class. To keep the security factor intact, the Laravel generated cookie always remain encrypted so that no client can either read it or make changes to it.

The cookie() method used in above code is capable of accepting 3 arguments at a time. The first argument will denote the cookie’s name. The second argument will be containing the value of the cookie. And the third argument will determine the duration for the existence of the cookie.

But, in case you want the cookie remain forever and do not get deleted after the given duration then you can use the following line of code.

$response->withCookie(cookie()->forever(‘name’, ‘value’));

[post_middile_section_ad]

How to Retrieve a Cookie?
A set cookie can be retrieved by the help of cookie() method. But, this cookie method will accept only 1 argument which will be the name of the cookie. For this, you need an instance of request, Illuminate\Http\Request. Later, this instance will be called by the cookie() method.

For your better understanding, take a look at the below provided sample code.

//’name’ is the name of the cookie to retrieve the value of $value = $request->cookie(‘name’);

Here, the illustration of the cookie

Step 1: Creation of a controller, CookieController to manipulate a cookie. To do this, execute the following code.

laravel> php artisan make:controller CookieController –plain

Step 2: After the successful creation of the controller, add the below code to the CookieController.php file. You can locate this file at app/Http/Controllers.