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

asilingas/cookie-consent-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup for Laravel Integration (via Symfony Bridge)
Since this is a Symfony bundle, Laravel developers will need to use **Symfony’s components** or **Laravel’s Symfony bridge** (e.g., `spatie/symfony-bridge`). Below are the minimal steps to integrate it into a Laravel project:

1. **Install via Composer**
   ```bash
   composer require asilingas/cookie-consent-bundle
  1. Bridge Symfony Components If not already set up, install Laravel’s Symfony bridge:

    composer require spatie/symfony-bridge
    
  2. Register the Bundle (via Symfony Kernel) Create a Symfony kernel class (e.g., app/Kernel.php) and register the bundle:

    use ConnectHolland\CookieConsentBundle\CHCookieConsentBundle;
    
    class Kernel extends \Symfony\Component\HttpKernel\Kernel
    {
        public function registerBundles()
        {
            return [
                new CHCookieConsentBundle(),
                // Other Symfony bundles...
            ];
        }
    }
    
  3. Configure Routing Add the bundle’s routes to Laravel’s Symfony router (e.g., in routes/symfony.php):

    use Symfony\Component\Routing\Loader\YamlFileLoader;
    use Symfony\Component\Routing\RouteCollection;
    
    $loader = new YamlFileLoader();
    $routes = $loader->load(__DIR__.'/../vendor/connectholland/cookie-consent-bundle/Resources/config/routing.yaml');
    $symfonyRouter->addCollection($routes);
    
  4. Publish Config & Assets Publish the bundle’s assets and config:

    php artisan vendor:publish --provider="ConnectHolland\CookieConsentBundle\CHCookieConsentBundle" --tag="config"
    php artisan vendor:publish --provider="ConnectHolland\CookieConsentBundle\CHCookieConsentBundle" --tag="public"
    
  5. Add to config/app.php Ensure the Symfony kernel is bootstrapped in Laravel’s service provider.

  6. First Use Case: Display Cookie Consent In a Blade template (or Twig via Laravel’s bridge), render the consent banner:

    @symfony\render_esi(route('ch_cookie_consent.show'))
    

    (Note: Laravel’s render_esi may require customization for Symfony routes.)


Implementation Patterns

Workflow: GDPR-Compliant Cookie Management

  1. Initial Load

    • Render the consent banner only if no prior consent exists (use chcookieconsent_isCookieConsentSavedByUser in Twig/Blade).
    • Example (Blade):
      @if(!chcookieconsent_isCookieConsentSavedByUser())
          @symfony\render_esi(route('ch_cookie_consent.show_if_cookie_consent_not_set'))
      @endif
      
  2. Category-Based Tracking

    • Check user consent for specific categories (e.g., analytics) before loading scripts:
      @if(chcookieconsent_isCategoryAllowedByUser('analytics'))
          <script src="https://analytics.example.com/script.js"></script>
      @endif
      
  3. Logging User Preferences

    • Enable use_logger: true in config to store consent in the database (requires Doctrine ORM).
    • Query logs for compliance audits:
      // Example: Fetch user consents (via Symfony Doctrine bridge)
      $consents = $entityManager->getRepository(CookieConsentLog::class)->findAll();
      
  4. Dynamic Theming

    • Override the default theme by publishing and modifying the SCSS file:
      php artisan vendor:publish --tag="public" --provider="ConnectHolland\CookieConsentBundle\CHCookieConsentBundle"
      
    • Update resources/sass/cookie_consent.scss and recompile assets.
  5. AJAX Submission

    • Use the bundled JavaScript for non-blocking submission:
      <script src="{{ asset('vendor/cookie-consent/js/cookie_consent.js') }}"></script>
      
    • Listen for submission events:
      document.addEventListener('cookie-consent-form-submit-successful', (e) => {
          console.log('Consent saved:', e.detail);
          // Trigger analytics scripts dynamically
      });
      
  6. Multi-Language Support

    • Translate category names and messages via Laravel’s translation system:
      # config/app.php
      'fallback_locale' => 'en',
      
    • Override translations in resources/lang/vendor/cookie-consent/.

Gotchas and Tips

Pitfalls

  1. Symfony-Laravel Integration Complexity

    • The bundle assumes a Symfony environment. Laravel developers must:
      • Use spatie/symfony-bridge or manually bridge Symfony components.
      • Handle route conflicts (e.g., ch_cookie_consent may clash with Laravel routes).
    • Fix: Prefix Symfony routes or use a subdomain for the consent endpoint.
  2. Doctrine ORM Dependency

    • Logging requires Doctrine. If not using ORM, disable use_logger or mock the CookieConsentLogger service.
  3. Asset Pipeline Conflicts

    • The bundle’s JS/CSS may conflict with Laravel Mix/Vite. Tip: Use mix.copy() to include the bundle’s assets:
      // webpack.mix.js
      mix.copy('vendor/cookie-consent/public/js/cookie_consent.js', 'public/js/');
      
  4. Cookie Domain/Path Issues

    • Cookies may not persist if the domain or path in config doesn’t match Laravel’s session settings.
    • Fix: Extend the CookieConsent service to merge with Laravel’s cookie settings:
      $this->app->extend('ch_cookie_consent.cookie_consent', function ($consent) {
          $consent->setCookieDomain(config('session.domain'));
          return $consent;
      });
      
  5. CSRF Protection in AJAX

    • If using AJAX submission, ensure Laravel’s CSRF token is included in the request. The bundle’s csrf_protection may need adjustment:
      ch_cookie_consent:
          csrf_protection: false  # Disable if handling CSRF manually
      
  6. Template Overrides in Laravel

    • Symfony 5’s template override path (app/templates/bundles/...) won’t work in Laravel. Tip: Use Laravel’s view overrides:
      php artisan vendor:publish --tag="views" --provider="ConnectHolland\CookieConsentBundle\CHCookieConsentBundle"
      
      Then modify resources/views/vendor/cookie-consent/cookie_consent.html.twig.

Debugging Tips

  1. Check Consent Status

    • Inspect cookies (Cookie_Consent, Cookie_Consent_Key) in browser dev tools. Missing cookies indicate rendering issues.
  2. Log Submission Events

    • Add a custom event listener to debug form submissions:
      $eventDispatcher->addListener('cookie_consent.form.submit', function ($event) {
          \Log::debug('Consent submitted:', $event->getData());
      });
      
  3. Verify Database Logs

    • If use_logger is enabled, check the cookie_consent_log table for entries. Anonymized IPs should appear as 0.0.0.0.
  4. Clear Cached Views

    • After template overrides, clear Laravel’s view cache:
      php artisan view:clear
      

Extension Points

  1. Custom Categories

    • Add new categories by extending the config and creating translations:
      ch_cookie_consent:
          categories:
              - 'analytics'
              - 'custom_category'  # Add new category
      
    • Translate in resources/lang/vendor/cookie-consent/en/category.custom_category.php:
      return ['Custom Category'];
      
  2. Custom Storage Backend

    • Replace the default cookie storage by binding a custom CookieConsentStorage service:
      $this->app->bind('ch_cookie_consent.storage', function () {
          return new CustomCookieConsentStorage();
      });
      
  3. Event-Driven Extensions

    • Listen to the cookie-consent.form.submit event to trigger custom logic (e.g., sync with a CRM):
      $eventDispatcher->addListener('cookie_consent.form.submit', function ($event) {
          // Sync with external service
          ExternalService::recordConsent($event->getData());
      });
      
  4. Headless Mode (APIs)

    • For APIs, bypass the UI and set consent via HTTP headers or middleware:
      $request->headers->set('X-Cookie-Consent', '{"analytics": true}');
      
    • Extend the CookieConsentChecker to parse headers instead of cookies.

---
```markdown
## Laravel-Specific Notes
- **Blade vs. Twig**: Replace Twig functions (`chcookieconsent_isCategoryAllowedByUser`) with Laravel
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky