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 Bundle Laravel Package

chaplean/cookie-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for First Use

  1. Installation Run composer require chaplean/cookie-bundle in your Laravel project (note: this is a Symfony bundle, but can be adapted for Laravel via bridge packages like symfony/bundle or manual integration).

  2. Service Provider Registration Register the bundle in config/app.php under providers:

    'providers' => [
        // ...
        Chaplean\Bundle\CookieBundle\ChapleanCookieBundle::class,
    ],
    
  3. Configuration Publish the config file (if available) or manually define in config/services.php:

    'chaplean_cookie' => [
        'learn_more' => '/privacy-policy', // Required URL for cookie details
        'translations' => [], // Optional translation overrides
    ],
    
  4. Route Inclusion Add the bundle’s routes in routes/web.php:

    Route::prefix('/')->group(function () {
        require __DIR__.'/vendor/chaplean/cookie-bundle/Resources/config/routing.yml';
    });
    
  5. Frontend Integration Include the headband script in your layout (e.g., resources/views/layouts/app.blade.php):

    <script src="{{ asset('vendor/chaplean/cookie-bundle/js/headband.js') }}"></script>
    
  6. Trigger Cookie Banner Call the JavaScript method to display the banner (e.g., in app.js):

    document.addEventListener('DOMContentLoaded', () => {
        window.ChapleanCookie.init();
    });
    

First Use Case: Display a cookie consent banner on page load, with a "Learn More" link pointing to your privacy policy.


Implementation Patterns

Core Workflows

  1. Dynamic Cookie Banner

    • Use the bundle to show/hide the banner based on user consent (e.g., via localStorage or cookies).
    • Example: Check for consent on route middleware:
      public function handle($request, Closure $next) {
          if (!$request->user()->hasCookieConsent()) {
              return redirect()->route('chaplean_cookie_banner');
          }
          return $next($request);
      }
      
  2. Translation Management

    • Override translations in config/services.php:
      'translations' => [
          'accept' => 'Agree and Proceed',
          'decline' => 'Decline Cookies',
      ],
      
    • Fallback to bundle defaults if keys are missing.
  3. Asset Integration

    • Bundle includes JavaScript/CSS for the banner. Use Laravel Mix to compile if needed:
      // webpack.mix.js
      mix.js('resources/js/app.js', 'public/js')
           .copy('vendor/chaplean/cookie-bundle/js/headband.js', 'public/js');
      
  4. Custom Styling

    • Override default styles via public/css/headband.css or inline styles:
      <style>
          .chaplean-cookie-banner { background: #f0f0f0; }
      </style>
      
  5. API for Consent Tracking

    • Extend the bundle to log consent status to a database:
      // In a service
      public function logConsent($userId, $consented) {
          Consent::create([
              'user_id' => $userId,
              'consented' => $consented,
              'ip_address' => request()->ip(),
          ]);
      }
      

Integration Tips

  • Laravel-Specific Adaptations:
    • Replace Symfony’s Container calls with Laravel’s app() or config().
    • Use Laravel’s asset() helper for paths instead of Symfony’s path().
  • Event-Driven Extensions:
    • Listen for chaplean.cookie.accepted or chaplean.cookie.declined events (if the bundle emits them) to trigger analytics or other actions.
  • Testing:
    • Mock the JavaScript banner in PHPUnit using Laravel’s Pest or BrowserKit:
      $response = $this->get('/');
      $response->assertSee('Cookie Consent Banner');
      

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Mismatch

    • The bundle assumes Symfony’s Container and Twig. For Laravel:
      • Replace container.get() with app() or config().
      • Use Blade instead of Twig templates (manually include the JS/CSS).
    • Fix: Wrap the bundle in a Laravel-compatible facade or use a bridge package like symfony/bundle.
  2. Outdated Dependencies

    • Last release in 2019 may conflict with modern Laravel (v9+) or PHP (8.1+).
    • Fix: Fork the repo and update dependencies (e.g., symfony/dependency-injection to ^6.0).
  3. Missing JavaScript Initialization

    • The banner won’t appear if ChapleanCookie.init() isn’t called.
    • Fix: Ensure the script is loaded after DOM ready (use DOMContentLoaded or jQuery’s $(document).ready()).
  4. Assetic Dependency

    • The README mentions Assetic (Symfony), which isn’t used in Laravel.
    • Fix: Ignore this step or manually include the JS/CSS files.
  5. No Built-in Consent Storage

    • The bundle doesn’t persist consent status by default.
    • Fix: Use Laravel’s session() or cookie() to store consent:
      // After accepting cookies
      $request->session()->put('cookie_consent', true);
      
  6. Routing Conflicts

    • The bundle’s routes may clash with existing Laravel routes (e.g., /cookie).
    • Fix: Override the route prefix in routes/web.php:
      Route::prefix('admin')->group(function () {
          require __DIR__.'/vendor/chaplean/cookie-bundle/Resources/config/routing.yml';
      });
      

Debugging Tips

  1. Check JavaScript Errors

    • Open browser dev tools (F12) to verify ChapleanCookie is defined and init() runs without errors.
    • Common Issue: Missing headband.js path. Use {{ asset('js/headband.js') }} in Blade.
  2. Verify Configuration

    • Dump the config to ensure learn_more URL is set:
      dd(config('chaplean_cookie'));
      
  3. Inspect Network Requests

    • Confirm the banner’s JS/CSS files load (check the "Network" tab in dev tools).
  4. Log Consent Events

    • Add debug logs in a custom service:
      Log::info('Cookie consent status:', ['status' => $consented]);
      

Extension Points

  1. Custom Banner Templates

    • Override the default Twig template by copying vendor/chaplean/cookie-bundle/Resources/views/cookie.html.twig to resources/views/vendor/chaplean/cookie-bundle/cookie.html.twig and modify.
  2. Add Cookie Categories

    • Extend the bundle to support granular consent (e.g., analytics, marketing):
      // Custom JS extension
      window.ChapleanCookie.categories = ['analytics', 'marketing'];
      
  3. Server-Side Consent Validation

    • Create a middleware to block tracking scripts if consent is missing:
      public function handle($request, Closure $next) {
          if (!$request->session()->has('cookie_consent')) {
              // Disable Google Analytics, etc.
              app()->singleton(GoogleAnalytics::class, function () {
                  return new NullAnalytics();
              });
          }
          return $next($request);
      }
      
  4. GDPR Compliance Hooks

    • Add a chaplean.cookie.accepted event listener to trigger data processing logs:
      Event::listen('chaplean.cookie.accepted', function ($user) {
          // Log to GDPR compliance system
      });
      
  5. Localization

    • Extend translations dynamically:
      config(['chaplean_cookie.translations' => [
          'learn_more' => trans('cookie.learn_more'),
      ]]);
      
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager