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

Symfony7 Cookie Consent Bundle Laravel Package

chanondb/symfony7-cookie-consent-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chanondb/symfony7-cookie-consent-bundle
    npm i bootstrap --save-dev
    

    Ensure bootstrap is installed for styling compatibility.

  2. Enable Bundle: Add to config/bundles.php:

    Chanondb\CookieConsentBundle\CookieConsentBundle::class => ['all' => true],
    
  3. Basic Configuration: Create config/packages/cookie_consent.yaml with default settings:

    cookie_consent:
      categories:
        - 'analytics'
        - 'marketing'
        - 'preferences'
    
  4. First Use Case: Trigger the consent modal by adding the Twig snippet to your base template (e.g., base.html.twig):

    {{ cookie_consent() }}
    

    This renders the Bootstrap 5-styled consent modal.


Implementation Patterns

Workflows

  1. Dynamic Category Management: Extend default categories in cookie_consent.yaml or via PHP:

    cookie_consent:
      categories:
        - 'analytics'
        - 'custom_category'  # Add custom category
    

    Use {{ cookie_consent_categories() }} in Twig to list all categories dynamically.

  2. Route-Specific Exclusions: Disable consent on specific routes (e.g., /privacy):

    cookie_consent:
      disabled_routes: ['privacy', 'imprint']
    

    Override per-controller in PHP:

    #[Route('/custom-page', name: 'custom_page', options: ['cookie_consent' => false])]
    
  3. CSRF Protection: Enable CSRF for form submissions (default: true):

    cookie_consent:
      csrf_protection: true
    

    Ensure Symfony\UX\TwigComponent\Security\CsrfTokenGenerator is available.

  4. XHR Request Handling: Configure a dedicated route for AJAX submissions:

    cookie_consent:
      form_action: 'cookie_consent_submit'
    

    Create a route:

    # config/routes.yaml
    cookie_consent_submit:
      path: /cookie-consent
      controller: Chanondb\CookieConsentBundle\Controller\CookieConsentController::submit
    
  5. Logging User Actions: Enable database logging:

    cookie_consent:
      use_logger: true
    

    Requires a CookieConsent entity (see Extension Points).


Integration Tips

  • Twig Extensions: Use cookie_consent_is_accepted(), cookie_consent_get_categories() to conditionally load scripts/styles:

    {% if cookie_consent_is_accepted('analytics') %}
      {{ include('analytics_script.html.twig') }}
    {% endif %}
    
  • JavaScript Integration: Listen for consent events via:

    document.addEventListener('cookieConsentAccepted', (e) => {
      console.log('Categories accepted:', e.detail.categories);
    });
    
  • Laravel Adaptation: Since this is a Symfony bundle, wrap it in a Laravel package (e.g., using spatie/symfony-bundle) or use its logic as a reference for a custom Laravel solution. Key takeaways:

    • Use middleware to block resources until consent.
    • Store consent in Laravel’s session or cookie facade.
    • Example middleware:
      public function handle($request, Closure $next) {
          if (!$request->cookie('cookie_consent') && !$request->routeIs('cookie_consent')) {
              return redirect()->route('cookie_consent.show');
          }
          return $next($request);
      }
      

Gotchas and Tips

Pitfalls

  1. Symfony-Specific Dependencies:

    • The bundle assumes Symfony’s HttpFoundation, SecurityBundle, and Twig. In Laravel:
      • Replace Request with Laravel’s Illuminate\Http\Request.
      • Mock Symfony’s CsrfTokenManager with Laravel’s csrf_token() helper.
      • Use Session::get() instead of Symfony’s session->get().
  2. Bootstrap 5 Conflicts:

    • Ensure no duplicate Bootstrap JS/CSS is loaded. Use webpack.mix.js to merge assets:
      mix.js('resources/js/app.js', 'public/js')
          .postCss('resources/css/app.css', 'public/css', [
              require('postcss-import'),
              require('tailwindcss'),
          ]);
      
  3. CSRF Token Mismatch: If csrf_protection: true fails, verify:

    • The _csrf_token is passed in the form.
    • The token generator is registered (Symfony’s security.csrf.token_manager).
  4. Route Name Collisions: The form_action route must match exactly. Use absolute paths if needed:

    form_action: '/cookie-consent/submit'
    
  5. Database Logging:

    • If use_logger: true, ensure the CookieConsent entity and migration exist. Adapt the Symfony entity to Laravel’s Eloquent:
      // app/Models/CookieConsent.php
      class CookieConsent extends Model {
          protected $fillable = ['user_id', 'categories', 'accepted_at'];
      }
      

Debugging

  1. Consent Not Showing:

    • Check bundles.php for the bundle’s inclusion.
    • Verify {{ cookie_consent() }} is in the Twig template.
    • Clear cache: php bin/console cache:clear (Symfony) or php artisan cache:clear (Laravel).
  2. Cookies Not Setting:

    • Ensure http_only: false if testing locally (default: true).
    • Check browser dev tools (Application > Cookies) for cookie_consent_* cookies.
  3. CSRF Errors:

    • Disable temporarily for testing:
      csrf_protection: false
      
    • Verify the token is included in the form submission.
  4. Logger Not Working:

    • Confirm the CookieConsent entity is registered in Symfony’s doctrine or Laravel’s Model.
    • Check database tables for cookie_consents table.

Extension Points

  1. Custom Categories: Extend the Category enum in PHP:

    // src/Enum/CookieCategory.php
    namespace App\Enum;
    enum CookieCategory: string {
        case Analytics = 'analytics';
        case Custom = 'custom_category'; // Add new category
    }
    

    Update cookie_consent.yaml to include the new category.

  2. Custom Storage: Override cookie storage by binding a custom service:

    # config/services.yaml
    services:
        Chanondb\CookieConsentBundle\Storage\CookieStorage:
            arguments:
                $storage: '@app.custom_cookie_storage'
    

    Implement CookieStorageInterface in Laravel:

    class CustomCookieStorage implements CookieStorageInterface {
        public function get($name) {
            return cookie($name);
        }
        public function set($name, $value, $minutes) {
            return response()->cookie($name, $value, $minutes);
        }
    }
    
  3. Custom Templates: Override Twig templates by copying from: vendor/chanondb/symfony7-cookie-consent-bundle/resources/views/ to: templates/bundles/cookieconsent/.

  4. Event Listeners: Subscribe to consent events (Symfony):

    // src/EventListener/CookieConsentListener.php
    class CookieConsentListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                CookieConsentEvents::ACCEPTED => 'onConsentAccepted',
            ];
        }
        public function onConsentAccepted(CookieConsentEvent $event) {
            // Log or trigger actions
        }
    }
    

    In Laravel, use events or service providers to hook into consent logic.

  5. Laravel-Specific Adaptations:

    • Replace Symfony’s EventDispatcher with Laravel’s Event facade.
    • Use Laravel’s Cookie facade for storage:
      Cookie::queue('cookie_consent', $value, $minutes);
      
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