Laravel

Laravel Cookies vs Javascript

Creating cookies in Laravel:

// Stores encrypted cookie.
Cookie::queue(Cookie::make('name', 'value', $minutes)); 

Default Laravel encrypts the when using Cookie::make and decrypts when getting cookie using Laravel.

// Get and decrypts the cookie.
Cookie::get('name');

Retrieving Cookies From Requests

All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. To retrieve a cookie value from the request, use the cookie method on a Illuminate\Http\Request instance:

$value = $request->cookie('name');

Alternatively, you may use the Cookie facade to access cookie values:

$value = Cookie::get('name');

Laravel uses the APP_KEY to encrypt & decrypt the cookie, that’s mean encrypted cookies are only readable for the Laravel app with used APP_KEY.

And jQuery or javascript are not able to decrypt it, as I faced the issue and found solution in Laravel documentation.

There is a solution provided by Laravel to whitelist cookies not to be encrypted. In EncryptCookies.php middleware you can list all of the cookies you don’t want to be encrypted or in other words those cookies need to be read by jQuery or Javascript.

Open your EncryptCookies.php file and add following block to whitelist cookies.

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        'my_non_encrypted_cookie',
    ];
}

That’s it.

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk