Creating an encrypted cookie value in Laravel - Rocketeers

  [ Rocketeers ](/)   

[Login](https://rocketeersapp.com) 

 On this page

 Knowledge
---------

Creating an encrypted cookie value in Laravel
=============================================

### [\#Laravel](https://rocketee.rs/index.php/laravel)

 Published by [Mark van Eijk](https://rocketee.rs/index.php/author/mark-van-eijk) on March 8, 2023 · 1 minute read

Laravel can encrypt cookies automatically using the `\App\Http\Middleware\EncryptCookies::class` middleware. It's so easy, you don't have to think about it when adding your cookies to the response.

But when you want to hit your own application with a request that needs a certain cookie, you can't simply add the cookie to the HTTP request and you also cannot encrypt it using the `encrypt()` helper. This is because cookies need a different treatment when creating the exact encrypted cookie value.

When digging in the source of Laravel we found the following code and we wrapped it up in a helper, because we have a specific use case for an application that needs to perform HTTP requests to itself, with some encrypted cookies.

Here we go, this helper can be added to any file your keeping your little helpers in:

 ```
if (! function_exists('encrypted_cookie_value')) {
    function encrypted_cookie_value(string $name, string $value): string
    {
        $encrypter = app(Illuminate\Encryption\Encrypter::class);

        return $encrypter->encrypt(
            CookieValuePrefix::create($name, $encrypter->getKey()).$value,
            false
        );
    }
}

```

### Subscribe to our newsletter

Do you want to receive regular updates with fresh and exclusive content to learn more about web development, hosting, security and performance? Subscribe now!

  Fill in your email address to receive updates  Subscribe 

#### More in [\#Laravel](https://rocketee.rs/index.php/laravel)

- [How to use different PHP versions with Laravel Valet](https://rocketee.rs/index.php/different-php-versions-laravel-valet)
- [Disable cookies in Laravel](https://rocketee.rs/index.php/disable-cookies-in-laravel)
- [Logging in Laravel](https://rocketee.rs/index.php/laravel-logging)
- [How to check which Laravel version of your app is using](https://rocketee.rs/index.php/check-laravel-version)
- [Disable CSRF in Laravel](https://rocketee.rs/index.php/disable-csrf-in-laravel)
- [Laravel Valet](https://rocketee.rs/index.php/laravel-valet)

 [View all 19 articles →](https://rocketee.rs/index.php/laravel)
