Retrieving Cookie Data
You can use {{ cookie }}
as a tag pair to access any cookie data that has been set.
{{ cookie }} {{ oreo }}{{ /cookie }}
Yum yum yum.
You can also retrieve single variables with a single tag syntax.
{{ cookie:oreo }}
Checking
You can check if a cookie exists with cookie:has.
{{ if {cookie:has key="has_voted"} === true }} You already voted. Thank you!{{ /if }}
Aliasing
If you need extra markup around your cookie data, you can alias a new child array variable.
{{ cookie as="snack" }} {{ snack }} {{ message }} {{ /snack }}{{ /cookie }}
Setting
You can set a cookie with cookie:set
:
{{ cookie:set my_key="my_value" }}
You can optionally set a number of minutes the cookie is valid for (60 by default):
{{ cookie:set my_key="my_value" minutes="3600" }}
You can set multiple cookies at once and reference interpolated data (references to variables).
{{ cookie:set likes="hats" :visited="url" }}
When you set a cookie, it will only be available on the next request.
Forgetting
You can remove cookies by passing the names of the variables into the keys
parameter. Pass multiple keys by delimiting them with a pipe.
{{ cookie:forget keys="likes|referral" }}
Accessing Cookies in JavaScript
By default, in Laravel, cookies are encrypted so you will not be able to access the values of any data you set outside of PHP. To exclude specific cookies from encryption follow the steps below:
Laravel 10
To prevent encryption you need to add an exception to the $except
array in your app/Http/Middleware/EncryptCookies.php
file.
/** * The names of the cookies that should not be encrypted. * * @var array */protected $except = [ 'cookie_name',];
Laravel 11
To prevent encryption you need to use the encryptCookies
method in your application's bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) { $middleware->encryptCookies(except: [ 'cookie_name', ]);})