Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cookie Consent Bundle Laravel Package

dimiceli/cookie-consent-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dimiceli/cookie-consent-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Dimiceli\CookieConsentBundle\DimiceliCookieConsentBundle::class => ['all' => true],
    ];
    
  2. Configuration: Publish the default config:

    php bin/console dimiceli:cookie-consent:install
    

    Edit config/packages/dimiceli_cookie_consent.yaml to define:

    • Cookie domains (e.g., analytics, marketing)
    • Default consent state (accept, reject, or prompt)
    • Cookie expiration (e.g., 365 days)
  3. First Use Case: Add the Twig extension to your base template (templates/base.html.twig):

    {{ include('DimiceliCookieConsentBundle::cookieConsent.html.twig') }}
    

    This renders the consent banner with auto-generated JavaScript for tracking.


Implementation Patterns

Core Workflow

  1. Define Cookie Domains: Extend the config to categorize cookies (e.g., analytics, ads, functionality):

    dimiceli_cookie_consent:
        domains:
            analytics:
                - google-analytics
                - matomo
            ads:
                - google-adwords
    
  2. Customize the Banner: Override the default Twig template (templates/DimiceliCookieConsentBundle/cookieConsent.html.twig) to:

    • Change button labels (e.g., "Accept All" → "Allow Cookies").
    • Add custom CSS classes for styling.
    • Include a link to your privacy policy.
  3. Dynamic Consent Handling: Use the CookieConsent service in controllers to check/revoke consent:

    use Dimiceli\CookieConsentBundle\Service\CookieConsent;
    
    public function someAction(CookieConsent $cookieConsent)
    {
        if (!$cookieConsent->isAccepted('analytics')) {
            return $this->redirectToRoute('home'); // Redirect if no consent
        }
        // Proceed with analytics...
    }
    
  4. JavaScript Integration: The bundle auto-generates JS to set cookies and track consent. Extend it via assets/javascripts/cookie-consent.js:

    document.addEventListener('cookieConsentAccepted', function(e) {
        // Custom logic after acceptance (e.g., load scripts)
        if (e.detail.domains.includes('analytics')) {
            loadGoogleAnalytics();
        }
    });
    
  5. API/Headless Use: For SPAs or APIs, use the CookieConsent service to validate consent in requests:

    $consent = $cookieConsent->getConsent();
    if (!$consent->isAccepted('functionality')) {
        throw new \RuntimeException('Functionality cookies required');
    }
    

Integration Tips

  • Laravel-Specific:

    • Use the Cookie facade to manually set consent cookies if needed:
      \Cookie::queue('cookie_consent', json_encode(['analytics' => true]), 365);
      
    • Integrate with Laravel’s VerifiedMiddleware to enforce consent for certain routes.
  • Analytics Packages:

    • For Laravel Analytics packages (e.g., spatie/laravel-analytics), wrap their initializers:
      if ($cookieConsent->isAccepted('analytics')) {
          Analytics::start();
      }
      
  • Localization: Translate the banner text via Symfony’s translation system:

    # config/packages/dimiceli_cookie_consent.yaml
    dimiceli_cookie_consent:
        translation_domain: 'cookie_consent'
    

    Add translations in translations/.


Gotchas and Tips

Pitfalls

  1. Cookie Domain Mismatches:

    • If cookies aren’t being set, verify the cookie_domain in config matches your app’s domain (e.g., .example.com for subdomains).
    • Debug with:
      php bin/console debug:config dimiceli_cookie_consent
      
  2. Caching Issues:

    • Clear cache after config changes:
      php bin/console cache:clear
      
    • The bundle caches consent data; test changes in an incognito window.
  3. JavaScript Conflicts:

    • Ensure the bundle’s JS loads after jQuery (if used) and before other scripts.
    • Disable auto-loading JS in config if you handle it manually:
      dimiceli_cookie_consent:
          auto_load_javascript: false
      
  4. GDPR Compliance Gaps:

    • The bundle handles consent but not data deletion requests. Implement a deleteConsent endpoint manually:
      public function deleteConsent(CookieConsent $cookieConsent)
      {
          $cookieConsent->rejectAll();
          return response()->json(['status' => 'deleted']);
      }
      
  5. Subdomain Isolation:

    • Cookies set on example.com won’t be shared with app.example.com. Use a shared domain (e.g., .example.com) in config.

Debugging

  1. Check Consent State: Inspect the cookie_consent cookie in browser dev tools. It stores JSON like:

    {"analytics": true, "ads": false, "last_updated": "2023-10-01"}
    
  2. Log Consent Events: Enable debug mode in config:

    dimiceli_cookie_consent:
        debug: true
    

    Logs will appear in var/log/dev.log.

  3. Test Edge Cases:

    • Force-reject all cookies via:
      php bin/console dimiceli:cookie-consent:reject-all
      
    • Test cookie expiration by setting expire_after to 1 minute in config.

Extension Points

  1. Custom Consent Logic: Override the CookieConsent service by binding your own class:

    // config/services.yaml
    services:
        Dimiceli\CookieConsentBundle\Service\CookieConsent:
            class: App\Service\CustomCookieConsent
            arguments: ['@dimiceli.cookie_consent.storage']
    
  2. Storage Backend: Extend the default cookie storage to use a database or session:

    // src/Service/CustomCookieConsent.php
    public function __construct(private StorageInterface $storage) {}
    

    Bind your storage in config/services.yaml.

  3. Event Listeners: Listen for consent changes via the cookie.consent.changed event:

    use Dimiceli\CookieConsentBundle\Event\ConsentChangedEvent;
    
    public function onConsentChanged(ConsentChangedEvent $event)
    {
        // Sync with CRM, log, etc.
    }
    

    Register in src/Kernel.php:

    protected function build(EventDispatcher $dispatcher)
    {
        $dispatcher->addListener(ConsentChangedEvent::NAME, [$this, 'onConsentChanged']);
    }
    
  4. Multi-Language Banners: Use Symfony’s translator to dynamically switch banner text based on locale. Extend the CookieConsentTwigExtension:

    // src/Twig/CustomCookieConsentExtension.php
    public function getBannerText(): string
    {
        return $this->translator->trans('cookie_consent.banner', [], 'cookie_consent');
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium