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

ekyna/cookie-consent-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ekyna/cookie-consent-bundle
    

    Ensure compatibility with your Laravel version (this bundle is Symfony-based; use Laravel Bridge if needed).

  2. Register Bundle In config/app.php, add the bundle to the providers array:

    Ekyna\Bundle\CookieConsentBundle\EkynaCookieConsentBundle::class,
    
  3. Add Routes Include the bundle’s routes in routes/web.php:

    require __DIR__.'/../../vendor/ekyna/cookie-consent-bundle/src/Resources/config/routing.yaml';
    
  4. First Use Case Add the Twig functions to your base template (resources/views/layouts/app.blade.php):

    @extends('layouts.base')
    @section('styles')
        <link href="{{ asset('vendor/ekyna/cookie-consent-bundle/css/cookie-consent.css') }}" rel="stylesheet">
    @endsection
    @section('scripts')
        @if(!ekyna_cookie_consent_category_allowed('all'))
            {!! ekyna_cookie_consent_render() !!}
        @endif
    @endsection
    

Implementation Patterns

Core Workflow

  1. Consent Collection

    • Use ekyna_cookie_consent_render() in your layout to display the consent modal.
    • Customize appearance via CSS (target .cookie-consent class).
  2. Conditional Script Loading Check consent for categories (analytic, marketing, social_network) before loading third-party scripts:

    {% if ekyna_cookie_consent_category_allowed('analytic') %}
        <script src="https://analytics.example.com/script.js"></script>
    {% endif %}
    
  3. API Integration For AJAX-heavy apps, use the API endpoint (/cookie-consent/accept) to programmatically handle consent:

    fetch('/cookie-consent/accept', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: JSON.stringify({ categories: ['analytic', 'marketing'] })
    });
    
  4. Laravel-Specific Adaptations

    • Service Provider: Extend functionality by binding the bundle’s services in AppServiceProvider:
      $this->app->bind('ekyna.cookie_consent.manager', function ($app) {
          return new CustomConsentManager($app['ekyna.cookie_consent.manager']);
      });
      
    • Middleware: Restrict routes based on consent:
      public function handle($request, Closure $next) {
          if (!$request->hasCookie('cookie_consent') || !ekyna_cookie_consent_category_allowed('required_category')) {
              abort(403);
          }
          return $next($request);
      }
      
  5. Dynamic Configuration Override default settings in config/packages/ekyna_cookie_consent.yaml:

    categories:
        analytic:
            name: "Analytics"
            description: "Track user behavior"
            default: false
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency

    • The bundle assumes Symfony’s kernel. For Laravel, use Laravel Bridge or wrap the bundle in a Laravel-compatible facade.
    • Workaround: Create a Laravel service to proxy Twig functions:
      class CookieConsentService {
          public function render(array $options = []) {
              // Delegate to Symfony's Twig environment if available
          }
      }
      
  2. Cookie Scope

    • Cookies are stored under cookie_consent. Ensure no conflicts with existing cookies (e.g., laravel_session).
    • Fix: Use config(['cookie_consent.cookie_name' => 'custom_consent']) to override.
  3. Twig Environment Mismatch

    • If using Laravel’s Blade, register the Twig functions manually:
      Blade::directive('ekyna_cookie_consent_render', function ($expr) {
          return "<?php echo app('ekyna.cookie_consent.twig')->render($expr); ?>";
      });
      
  4. CSRF Protection

    • The /cookie-consent/accept endpoint requires CSRF tokens. For AJAX, include:
      headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
      }
      

Debugging Tips

  1. Check Consent State Inspect the cookie_consent cookie or dump the manager:

    dd(app('ekyna.cookie_consent.manager')->getConsent());
    
  2. Log Consent Events Extend the manager to log actions:

    class CustomManager extends \Ekyna\Bundle\CookieConsentBundle\Manager {
        public function accept(array $categories) {
            \Log::info('Consent accepted', ['categories' => $categories]);
            return parent::accept($categories);
        }
    }
    
  3. Override Templates Customize the modal by copying vendor/ekyna/cookie-consent-bundle/Resources/views/ to resources/views/vendor/ekyna/cookie-consent-bundle/.

Extension Points

  1. Add Custom Categories Dynamically register categories via the manager:

    $manager->addCategory('custom', [
        'name' => 'Custom Tracking',
        'default' => false
    ]);
    
  2. Localization Override translations in config/packages/ekyna_cookie_consent.yaml:

    translations:
        en:
            accept: "Accept All"
            reject: "Reject All"
    
  3. Database Storage Replace the default cookie storage with a database-backed solution:

    $manager->setStorage(new DatabaseConsentStorage());
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui