DEV Community

Cover image for How Do You Set Cookie Consent in Laravel? 🍪
ThemeSelection for ThemeSelection

Posted on

How Do You Set Cookie Consent in Laravel? 🍪

In this tutorial, we are going to walk you through how to set up a cookie consent bar and get it working in your Laravel app. But before we dive into that, let's take a moment to understand what cookies are all about!

What are cookies?

Cookies are super important for how websites work and can improve your browsing experience! They are small files stored on your browser by websites for the betterment of your browsing experience. They can save information such as user preferences, website settings, and session details.

Besides, The cookies remain in your browser until they expire or are manually cleared. When you revisit a website, your browser sends the stored cookies back to the server, allowing the site to load with your previous preferences or settings, improving usability and personalization.

Why do we need cookie consent?

cookie consent

The privacy laws, the General Data Protection Regulation (GDPR) within the European Union and the California Consumer Privacy Act (CCPA) in the U.S., therefore require that websites inform users about data collection practices.

Consent ensures that the website complies with these laws, therefore avoiding penalties and ensuring transparent handling of data.

Cookies may collect personal data, for instance, browsing habits, preferences, and even location. Consent ensures that users know what data is being collected and how it will be used.

By seeking consent, the website is enabling users to determine whether they are comfortable with the data being collected. It aligns with the principle of user autonomy over personal information.

Proper information given regarding cookies and obtaining consent between the user and the website create trust. Users are likely to interact with websites which respect their privacy.

While some cookies, such as basic functionality cookies, may not need consent, others related to advertising, tracking, or analytics often do. Obtaining consent helps distinguish these cases while keeping the website user-friendly and compliant.

What is the spatie/laravel-cookie-consent package?

GitHub logo spatie / laravel-cookie-consent

Make your Laravel app comply with the crazy EU cookie law

Simple, customizable cookie consent message for Laravel

Latest Version on Packagist Software License run-tests Total Downloads

This package adds a simple, customizable cookie consent message to your site. When the site loads, the banner appears and lets users consent to cookies. Once consent is given, the banner hides and stays hidden.

What this package does not:

  • Include an option to 'Decline' all cookies, which might be required.
  • Block trackers and cookies before consent. You need to handle this yourself.
  • Include options for different consent categories like "Necessary" or "Marketing".

For more advanced cookie consent options in Laravel, consider these alternatives.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page

The spatie/laravel-cookie-consent package is a Laravel tool that adds a customizable cookie consent banner to your website, helping you comply with EU cookie laws. When users visit your site, the banner appears, allowing them to consent to cookie usage. Once consent is given, the banner hides and remains hidden on subsequent visits.

Key Features:

  • Customizable Consent Message: Easily modify the text and appearance of the consent banner to align with your website's design and messaging.
  • Automatic Handling: The package manages the display and hiding of the consent banner based on user interaction, simplifying compliance efforts.

Limitations:

  • No 'Decline' Option: The package does not include a 'Decline' button, which might be required for full compliance in certain jurisdictions.
  • Does Not Block Cookies Before Consent: It doesn't automatically block cookies or trackers before user consent; you'll need to implement this functionality yourself.
  • No Consent Categories: The package doesn't offer options for different consent categories like "Necessary" or "Marketing" cookies.

If you want more advanced cookie consent features, then an alternative is also available.

  • whitecube/laravel-cookie-consent
  • statikbe/laravel-cookie-consent

In this tutorial, we will utilize the spatie/laravel-cookie-consent package.

Installation

You can easily integrate this package into your existing project, or you can use the command below to create a new Laravel application.

  • Create a Laravel project.

    composer create-project --prefer-dist laravel/laravel fresh-laravel
    
    
  • Now, let's proceed with the project.

    cd fresh-laravel
    
    
  • We need to install the spatie/laravel-cookie-consent package. This package will automatically register itself upon installation.

    composer require spatie/laravel-cookie-consent
    
    
  • You may optionally choose to publish the configuration file.

    php artisan vendor:publish --provider="Spatie\\CookieConsent\\CookieConsentServiceProvider" --tag="cookie-consent-config"
    
    
  • The contents of the published configuration file are as follows:

    return [
    
        /*
         * Use this setting to enable the cookie consent dialog.
         */
        'enabled' => env('COOKIE_CONSENT_ENABLED', true),
    
        /*
         * The name of the cookie in which we store if the user
         * has agreed to accept the conditions.
         */
        'cookie_name' => 'laravel_cookie_consent',
    
        /*
         * Set the cookie duration in days.  Default is 365 * 20.
         */
        'cookie_lifetime' => 365 * 20,
    ];
    
    
  • The cookie domain is defined by the 'domain' key in the config/session.php file. Ensure that you add a value for SESSION_DOMAIN in your .env file. If you are using a URL with a port, such as 'localhost:3000', this package will not function properly until you make this adjustment.

To ensure that the cookie consent bar loads on every page, include @include('cookie-consent::index') in your application's entry point or the layout file.

Usages

Laravel cookie consent example

To enable the cookie consent bar, add the variable COOKIE_CONSENT_ENABLED to the .env file and set it to true. Once you have enabled it, a nice banner will appear like this:

When a user clicks the "Allow cookies" button to allow cookies, the laravel_cookie_consent variable is set to 1 in the browser's cookie storage. This value can be used to run or include any scripts in your application, such as Google Analytics code.

@if (!config('cookie-consent.enabled') || \\Illuminate\\Support\\Facades\\Cookie::get(config('cookie-consent.cookie_name')) !== null )
    // conditionally render code here
@endif

Enter fullscreen mode Exit fullscreen mode

All you need to do is create a basic cookie consent in a Laravel application.

Developing an advanced cookie management dashboard requires consideration of a user-friendly interface that enables users to turn on or off the cookie consent bar without changing the code.

We should also implement a feature to dynamically add scripts in our Laravel application, along with an option for users to opt in or opt out of cookie consent for each specific script.

No need to worry Jetship Laravel SaaS Boilerplate already includes these basic features and more!

Besides cookie consent functionality, the Jetship Laravel SaaS Starter Kit offers an impressive range of features, including:

  • A robust and secure authentication system to protect user accounts.
  • Integration with two leading payment gateways: Stripe and Lemon Squeezy.
  • A fully managed, SEO-friendly blog for content marketing.
  • Comprehensive roles and permissions management for fine-grained access control.
  • Reusable, niche-specific UI components to accelerate development.
  • And many other powerful tools to streamline your SaaS development.

You can explore the live demo here. Experience the difference the Jetship Laravel starter kit makes!

Laravel cookie consent demo

Conclusion:

Integrating a cookie consent banner into your Laravel application is a vital step toward ensuring compliance with privacy regulations like GDPR and CCPA. It not only fosters user trust but also enhances transparency regarding data collection and usage practices.

By leveraging the spatie/laravel-cookie-consent package, you can implement a fully customizable and user-friendly cookie consent solution with minimal effort. This package simplifies the process of informing users about cookies, managing their preferences, and adhering to legal requirements.

Additionally, with advanced tools like Jetship Laravel SaaS Boilerplate, you can take your application’s functionality to the next level—streamlining development while ensuring compliance with built-in cookie consent and other essential features.

With the right tools and a clear implementation strategy, you’re well on your way to creating a more transparent, user-focused experience. Start building applications that not only meet regulatory standards but also enhance user trust and engagement.

Happy coding!

Top comments (0)