It’s possible in our application, we set cookies on the JS side, but we want to use that from our back-end as well. We could use the $_COOKIE magic global, but if we use Laravel, we use the possibilities it offers. Let’s see how does it work.
Setting Cookies on the Front-End
In this post, we focus on existing cookies. If you are interested in how to handle them from the JavasScript, read the docs.
For now, let’s say we have an existing cookie with the “is-collapsed” key. We want to check the value from the back-end to perform some action on the server side.
Laravel and Cookies
We can access our cookies by the request()->cookie() method, or using the Cookie facade.
The problem is, if we want to reach our cookie, what we set on the front-end, we get null as a value. But is we use the $_COOKIE variable, we can access that, so that’s the proof the cookie exists. What’s the problem then?
By default, the framework brings a middleware for encrypting cookies. If we set a cookie from the back-end, it’s automatically encrypted so Laravel can read that. From the JS we don’t have any encryption, and that’s why we can’t access them from the framework.
How to Solve This?
In the app/Http/Kernel.php, in the web middleware group, we can find an EncryptCookies::class line. By commenting out the middleware, we can turn off the automatic encryption for cookies, but this approach is not the solution we want.
The suggested way is using the middleware and add some exceptions what does not need encryption, and Laravel should read them anyway. We can insert the exceptions to out middleware in the app/Http/Middlewares/EncryptCookies.php.
/** * The names of the cookies that should not be encrypted. * * @var array */ protected $except = [ 'is-collapsed', ];
By adding the name of the cookie to the except array, we able to read the cookies with the Cookie facade, or the request()->cookie() method.