Laravel Cookie - Get and set Cookies | W3Schools

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.

Here, is a sample code for your better understanding.

Also Read: Laravel Response

//Create a response instance
$response = new Illuminate\Http\Response(‘Hello World’);

//Call the withCookie() method with the response method
$response->withCookie(cookie(‘name’, ‘value’, $minutes));

//return the response
return $response;

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.

return $response;
}
public function getCookie(Request $request){
$value = $request->cookie(‘name’);
echo $value;
}
}

Step 3: Now, add the following lines of code to the routes.php. You can find this file at app/Http.

Route::get(‘/cookie/set’,’CookieController@setCookie’);
Route::get(‘/cookie/get’,’CookieController@getCookie’);

Step 4: Copy the URL: http://localhost:8000/cookie/set on the web server to set the cookie. You will get the following output.

[post_middile_section_ad]

Step 5: Now, to get the already set cookie. Paste the URL: http://localhost:8000/cookie/get to the PHP’s web server. The output of will appear like the following.