laravel-cookie-consent

repository·main·Indexed 19 days ago

https://github.com/whitecube/laravel-cookie-consent

A GDPR-compliant cookie consent management package for Laravel. It allows developers to register, categorize, and manage user consent for essential, analytics, and optional cookies using built-in Blade directives, a JavaScript library, and a dedicated Service Provider.

Tokens
10.9K
Snippets
46
Records
46
Agent score
65%

What's inside laravel-cookie-consent

  1. Registering cookies and choosing categories

    main

    Cookies should be grouped into categories to allow users to grant consent to groups of cookies rather than individual ones. The package provides three base categories:

    1. Cookies::essentials(): Required cookies that cannot be opted-out. Includes:
      • Cookies::essentials()->session(): Registers Laravel's session cookie.
      • Cookies::essentials()->csrf(): Registers Laravel's XSRF-TOKEN cookie.
    2. Cookies::analytics(): For statistics and data collection.
      • Cookies::analytics()->google(string $trackingId, bool $anonymizeIp): Automatically registers Google Analytics cookies and injects the necessary JS scripts into the <head> only when consent is granted.
    3. Cookies::optional(): For utility features. These can be opted-out, so always check for consent before relying on them.

    You can also create custom categories using the Cookies::category() method. Custom categories can be accessed via camel-case methods on the facade once defined.

    use Whitecube
    LaravelCookieConsent
    Facades
    Cookies;
    
    // Create a custom category
    $category = Cookies::category(key: 'my-custom-category');
    
    // Or with a custom class extending Whitecube\LaravelCookieConsent\CookiesCategory
    $category = Cookies::category(key: 'my-custom-category', maker: function(string $key) {
        return new MyCustomCategory($key);
    });
    
    // Access it via camel-case
    $category = Cookies::myCustomCategory();
  2. Register cookies in CookiesServiceProvider

    main

    To define which cookies your site uses, implement the registerCookies() method within your App\Providers\CookiesServiceProvider. You can categorize cookies into essentials(), analytics(), or optional() categories.

    Available registration patterns:

    • Essentials: Use Cookies::essentials() for strictly necessary cookies like session() or csrf().
    • Analytics: Use Cookies::analytics() for shorthand registration of tools like Google Analytics.
    • Optional: Use Cookies::optional() for custom cookies. You can chain methods like name(), description(), and duration() (in minutes). Use accepted() to define the logic that executes when a user consents to that specific cookie.
    namespace App\Providers;
    
    use Whitecube\LaravelCookieConsent\Consent;
    use Whitecube\LaravelCookieConsent\Facades\Cookies;
    use Whitecube\LaravelCookieConsent\CookiesServiceProvider as ServiceProvider;
    
    class CookiesServiceProvider extends ServiceProvider
    {
        protected function registerCookies(): void
        {
            if (app()->environment() === 'production') {
                // Register essentials
                Cookies::essentials()
                    ->session()
                    ->csrf();
        
                // Register analytics
                Cookies::analytics()
                    ->google(
                        id: config('cookieconsent.google_analytics.id'),
                        anonymizeIp: config('cookieconsent.google_analytics.anonymize_ip')
                    );
            
                // Register custom optional cookies
                Cookies::optional()
                    ->name('darkmode_enabled')
                    ->description('This cookie helps us remember your preferences regarding the interface\'s brightness.')
                    ->duration(120)
                    ->accepted(fn(Consent $consent, MyDarkmode $darkmode) => $consent->cookie(value: $darkmode->getDefaultValue()));
            }
        }
    }
  3. Publish and customize cookie consent views

    main

    To customize the look and feel of the cookie notice, you can publish the default Blade templates to your application. This allows you to modify the HTML structure and integrate your own CSS or Tailwind classes.

    Run the following command to copy the views to resources/views/vendor/cookie-consent:

    php artisan vendor:publish --tag=laravel-cookie-consent-views

    When rendered, the views have access to these variables:

    • $policy: The URL to your app's Cookie Policy page (configured in config/cookieconsent.php).
    • $cookies: The registered cookie categories and their definitions.
  4. Configure custom category translations

    main

    To add human-readable titles and descriptions to your custom categories, add entries to your translation files under the cookieConsent::cookies.categories.[category-key] key.

    return [
        // ...
        'categories' => [
            // ...
            'my-custom-category' => [
                'title' => 'My custom category of cookies',
                'description' => 'A short description of what these cookies are meant for.',
            ],
            // ...
        ],
    ];
  5. Publish and customize translation files

    main

    To change the text displayed in the cookie notice, you can publish the translation files. This allows you to support custom locales or modify existing strings.

    Run the following command to copy the translation files to your lang/vendor/cookieConsent directory:

    php artisan vendor:publish --tag=laravel-cookie-consent-lang
  6. Publish package files and configure Service Provider

    main

    After installation, you must publish the service provider and configuration files. Depending on your Laravel version, you will also need to manually register the CookiesServiceProvider.

    1. Publish the Service Provider: php artisan vendor:publish --tag=laravel-cookie-consent-service-provider

    2. Register the Service Provider:

      • Laravel 9 or 10: Add App\Providers\CookiesServiceProvider::class to the providers array in config/app.php. Ensure it is added after App\Providers\RouteServiceProvider::class.
      • Laravel 11 and above: Add App\Providers\CookiesServiceProvider::class to the array in bootstrap/providers.php.
    3. Publish the Configuration: php artisan vendor:publish --tag=laravel-cookie-consent-config

    // Laravel 9/10: config/app.php
    'providers' => ServiceProvider::defaultProviders()->merge([
        // ...
        App\Providers\RouteServiceProvider::class,
        // IMPORTANT: add the following line AFTER "App\Providers\RouteServiceProvider::class,"
        App\Providers\CookiesServiceProvider::class,
    ])->toArray(),
    
    // Laravel 11+: bootstrap/providers.php
    return [
        App\Providers\AppServiceProvider::class,
        App\Providers\CookiesServiceProvider::class,
    ];
  7. Add consent scripts and views to Blade templates

    main

    To display the cookie consent UI and ensure scripts are loaded correctly, use the provided Blade directives in your layout files.

    • @cookieconsentscripts: Place this in the <head> section. It loads the package's default JavaScript and allows for third-party scripts that require consent.
    • @cookieconsentview: Place this in the <body> section. It renders the actual consent alert or pop-up view.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <!-- ... -->
        @cookieconsentscripts
    </head>
    <body>
        <!-- ... -->
        @cookieconsentview
    </body>
    </html>
  8. Configure cookie domain for sub-domains

    main

    By default, cookie consent is stored for the current domain only. To allow a user's consent to persist across multiple sub-domains, update the domain setting in config/cookieconsent.php. Ensure you include a leading dot.

    'cookie' => [
        // ...
        'domain' => '.mydomain.com',
    ],
    'cookie' => [
        // ...
        'domain' => '.mydomain.com', // notice the leading "."
    ],
  9. Publish configuration, views, and language files

    main

    To customize the package, you can publish its assets using the following Artisan commands:

    • Configuration: php artisan vendor:publish --tag=laravel-cookie-consent-config
    • Views: php artisan vendor:publish --tag=laravel-cookie-consent-views
    • Translations: php artisan vendor:publish --tag=laravel-cookie-consent-lang
    • Custom Service Provider Stub: php artisan vendor:publish --tag=laravel-cookie-consent-service-provider
    # Publish configuration
    php artisan vendor:publish --tag=laravel-cookie-consent-config
    
    # Publish views
    php artisan vendor:publish --tag=laravel-cookie-consent-views
    
    # Publish language files
    php artisan vendor:publish --tag=laravel-cookie-consent-lang
  10. Generate a dynamic Cookie Policy page

    main

    You can use the Whitecube\LaravelCookieConsent\Facades\Cookies facade to automatically generate a detailed list of cookies for your legal pages. This ensures your policy stays in sync with your code definitions.

    Example of iterating through categories and cookies in a Blade template:

    @foreach(Cookies::getCategories() as $category)
        <caption>{{ $category->title }}</caption>
        @foreach($category->getCookies() as $cookie)
            <tr>
                <td>{{ $cookie->name }}</td>
                <td>{{ $cookie->description }}</td>
                <td>{{ $cookie->duration }}</td>
            </tr>
        @endforeach
    @endforeach
    <h1>Cookie Policy</h1>
    
    <p>...</p>
    
    <h2>How do we use cookies?</h2>
    
    @foreach(Cookies::getCategories() as $category)
    <table
        <caption>{{ $category->title }}</caption>
        <thead
            <tr
                <th>Cookie</th>
                <th>Description</th>
                <th>Duration</th>
            </tr>
        </thead>
        <tbody>
            @foreach($category->getCookies() as $cookie)
            <tr>
                <td>{{ $cookie->name }}</td>
                <td>{{ $cookie->description }}</td>
                <td>{{ \Carbon\Carbon::now()->diffForHumans(\Carbon\Carbon::now()->addMinutes($cookie->duration), true) }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @endforeach
  11. Use @cookieconsentbutton directive for consent actions

    main

    The @cookieconsentbutton() Blade directive is used to render buttons that trigger specific consent API routes. These buttons are wrapped in a <form> element to ensure they work even when JavaScript is disabled.

    Available actions:

    • accept.all: Targets the "consent to all cookies" route.
    • accept.essentials: Targets the "consent to essential cookies only" route.
    • accept.configuration: Targets the "consent to custom cookies selection" route. Note: This requires the selected cookie categories to be sent in the request payload.
    • reset: Targets the "reset cookie configuration" route.

    You can customize the button's label and HTML attributes (like id or class) by passing them as arguments.

    @cookieconsentbutton(
        action: 'reset',
        label: 'Manage cookies',
        attributes: [
            'id' => 'reset-button',
            'class' => 'btn'
        ]
    )