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

Laravel Cookie Consent Laravel Package

devrabiul/laravel-cookie-consent

GDPR-compliant cookie consent for Laravel with one-click install. Lightweight, no frontend deps, responsive banner with dark mode, RTL/i18n, and granular category controls (necessary/analytics/marketing). Fully customizable colors, text, and layout via config.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require devrabiul/laravel-cookie-consent
    php artisan vendor:publish --provider="Devrabiul\CookieConsent\CookieConsentServiceProvider"
    
  2. Basic Blade Integration:
    <!-- In <head> -->
    {!! CookieConsent::styles() !!}
    
    <!-- Before </body> -->
    {!! CookieConsent::scripts() !!}
    
  3. First Use Case:
    • Enable GDPR compliance with a pre-configured banner.
    • Test by visiting your site; the banner should appear for first-time visitors.

Key Configuration

  • Review config/cookie-consent.php for default settings (e.g., cookie lifetimes, categories).
  • Set environment variables (e.g., COOKIE_CONSENT_ANALYTICS=true) to enable/disable categories.

Implementation Patterns

Workflow: Adding Cookie Consent to a Project

  1. Initial Setup:

    • Publish config and assets.
    • Configure cookie categories (e.g., necessary, analytics, marketing) in config/cookie-consent.php.
    • Define JavaScript actions (e.g., loadGoogleAnalytics) in your assets file.
  2. Dynamic Configuration:

    • Override settings per page by passing options to CookieConsent::scripts():
      {!! CookieConsent::scripts([
          'cookie_lifetime' => 30,
          'theme' => 'trust-green',
          'disable_page_interaction' => false,
      ]) !!}
      
  3. Integration with Analytics/Marketing:

    • Use js_action in cookie categories to trigger scripts (e.g., Google Analytics, Facebook Pixel) only after consent:
      'analytics' => [
          'js_action' => 'loadGoogleAnalytics',
          'enabled' => env('COOKIE_CONSENT_ANALYTICS', false),
      ],
      
    • Implement the loadGoogleAnalytics() function in your JavaScript file.
  4. Localization:

    • Translate strings via Laravel’s localization system (e.g., CookieConsent::translate('Privacy Policy')).
    • Use RTL support by adding dir="rtl" to <body> and setting rtl_enabled: true in config.
  5. Dark Mode:

    • Enable auto-detection by setting theme: 'dark' in config or adding theme="dark" to <body>.
  6. Preferences Modal:

    • Enable with 'preferences_modal_enabled': true in config.
    • Customize layout (bar or box) and content (e.g., cookie_modal_intro).

Common Patterns

  • Conditional Loading: Use disable_page_interaction: true to block page interaction until consent is given.
  • Category-Specific Consent: Lock necessary cookies ('locked': true) while allowing users to toggle others.
  • Compliance Links: Add a "Change Preferences" link anywhere:
    <a onclick="showHideToggleCookiePreferencesModal()">Cookie Settings</a>
    

Gotchas and Tips

Pitfalls

  1. Asset Paths:

    • If using a custom asset URL (e.g., CDN), ensure COOKIE_CONSENT_ASSET_URL is set correctly. Localhost may require null.
    • Fix: Set COOKIE_CONSENT_ASSET_URL=null in .env for local development.
  2. Cookie Conflicts:

    • Existing cookies may interfere with the package’s functionality.
    • Fix: Clear old cookies or adjust cookie_prefix in config (e.g., 'cookie_prefix': 'MyApp_').
  3. JavaScript Actions:

    • Forgetting to define js_action functions (e.g., loadGoogleAnalytics) will break script loading.
    • Fix: Implement all js_action functions in your global JS file.
  4. Caching Issues:

    • Browser cache may retain old consent states.
    • Fix: Use reject_lifetime: 0 to force re-prompting or clear cookies manually.
  5. Dark Mode Conflicts:

    • Custom CSS may override dark mode styles.
    • Fix: Use !important sparingly or inspect the generated classes (e.g., .cookie-consent-dark).

Debugging Tips

  • Check Consent State: Inspect cookies (e.g., Laravel_App_consent) or use CookieConsent::getConsent() in Laravel.
  • Log Events: Enable COOKIE_CONSENT_LOG_EVENTS=true to debug consent changes via Laravel logs.
  • Test RTL/Localization: Use dir="rtl" and lang="ar" attributes to verify RTL and translation support.

Extension Points

  1. Custom Themes:

    • Override default styles by publishing the package’s assets:
      php artisan vendor:publish --tag=cookie-consent-assets
      
    • Modify resources/views/vendor/cookie-consent/ files.
  2. Event Listeners:

    • Listen for consent events (e.g., CookieConsentAccepted, CookieConsentRejected) to log or trigger actions:
      // In EventServiceProvider
      protected $listen = [
          'Devrabiul\CookieConsent\Events\CookieConsentAccepted' => [
              'App\Listeners\LogConsentEvent',
          ],
      ];
      
  3. API Integration:

    • Use CookieConsent::getConsent() to fetch consent data in API routes:
      $consent = CookieConsent::getConsent();
      return response()->json(['analytics_enabled' => $consent->analytics]);
      
  4. Multi-Tenant Support:

    • Store consent per tenant by overriding the cookie handler:
      // In CookieConsentServiceProvider
      $this->app->singleton('cookie-consent.handler', function () {
          return new \App\Services\TenantCookieConsentHandler();
      });
      

Pro Tips

  • Performance: Disable disable_page_interaction if you’re using a lightweight analytics script.
  • A/B Testing: Use different theme_preset values (e.g., modern-blue, trust-green) to test user engagement.
  • Compliance Audits: Enable COOKIE_CONSENT_LOG_EVENTS and review logs for granular consent tracking.
  • Localization: Pre-translate strings in resources/lang/ to avoid runtime translation delays.

```markdown
## Advanced: Dynamic Configuration via Middleware
Create middleware to dynamically adjust consent settings (e.g., disable analytics for admins):
```php
// app/Http/Middleware/CookieConsentMiddleware.php
public function handle($request, Closure $next) {
    if (auth()->check() && auth()->user()->isAdmin) {
        config(['laravel-cookie-consent.cookie_categories.analytics.enabled' => false]);
    }
    return $next($request);
}

Register the middleware in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\CookieConsentMiddleware::class,
];

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport