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 setup and no frontend dependencies. Fully customizable banners with RTL/i18n, dark mode, responsive UI, and granular category controls (necessary/analytics/marketing) for enterprise-grade compliance.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require devrabiul/laravel-cookie-consent
    php artisan vendor:publish --provider="Devrabiul\CookieConsent\CookieConsentServiceProvider"
    

    This publishes the default config, views, and assets to config/cookie-consent.php, resources/views/vendor/cookie-consent/, and public/vendor/cookie-consent/.

  2. Basic Integration: Add the package's styles and scripts to your Blade template:

    <!DOCTYPE html>
    <html>
    <head>
        {!! CookieConsent::styles() !!}
    </head>
    <body>
        <!-- Your content -->
        {!! CookieConsent::scripts() !!}
    </body>
    </html>
    
  3. First Use Case: Enable cookie consent for analytics and marketing in .env:

    COOKIE_CONSENT_ANALYTICS=true
    COOKIE_CONSENT_MARKETING=true
    

    This will automatically show the consent banner on page load, allowing users to accept/reject cookies.

Where to Look First

  • Config File: config/cookie-consent.php – Centralize all settings (cookie categories, lifetimes, themes, translations).
  • Blade Directives: CookieConsent::styles() and CookieConsent::scripts() – Minimal integration points.
  • Cookie Categories: Define granular consent controls (e.g., necessary, analytics, marketing) in the config.
  • Live Demo: rixetbd.com/docs?package=laravel-cookie-consent – Visualize layouts and behaviors.

Implementation Patterns

Core Workflows

  1. Consent Management:

    • Use CookieConsent::hasConsent('analytics') in your controllers to check if a user has consented to a category.
    • Example:
      if (CookieConsent::hasConsent('analytics')) {
          Analytics::trackPageView();
      }
      
  2. Dynamic Script Loading:

    • Define JavaScript functions (e.g., loadGoogleAnalytics) in your assets file (e.g., public/js/cookie-consent.js).
    • Map these functions to cookie categories in the config:
      'cookie_categories' => [
          'analytics' => [
              'js_action' => 'loadGoogleAnalytics',
          ],
      ],
      
    • The package will automatically execute these functions after consent is granted.
  3. Multi-Language Support:

    • Publish translations via php artisan vendor:publish --tag=cookie-consent-lang.
    • Override translations in resources/lang/{locale}/cookie-consent.php:
      return [
          'Privacy Policy' => 'Datenschutzrichtlinie',
      ];
      
  4. Theme Customization:

    • Choose a preset (basic, modern-blue, trust-green, etc.) in the config:
      'theme_preset' => 'trust-green',
      
    • Override CSS variables in public/css/cookie-consent.css for full control.
  5. Dark Mode:

    • Enable dark mode by adding theme="dark" to the <body> tag or setting:
      'theme' => 'dark',
      
    • The package auto-detects system preferences if theme="auto".

Integration Tips

  • Middleware for Protected Routes: Create middleware to block analytics scripts if consent is missing:

    public function handle($request, Closure $next) {
        if (!$request->user() && !CookieConsent::hasConsent('analytics')) {
            abort(403, 'Analytics consent required.');
        }
        return $next($request);
    }
    
  • Event Listeners: Dispatch custom events when consent changes:

    CookieConsent::consentChanged(function ($category, $accepted) {
        event(new CookieConsentChanged($category, $accepted));
    });
    
  • API Consent Checks: Pass consent status via API responses:

    return response()->json([
        'data' => $data,
        'consent' => [
            'analytics' => CookieConsent::hasConsent('analytics'),
            'marketing' => CookieConsent::hasConsent('marketing'),
        ],
    ]);
    
  • Localization: Use the CookieConsent::translate() helper for dynamic text:

    <p>{!! CookieConsent::translate('cookie_description') !!}</p>
    

Gotchas and Tips

Pitfalls

  1. Asset Paths in Local Development:

    • If using COOKIE_CONSENT_ASSET_URL, set it to null in .env during local testing to avoid CORS issues:
      COOKIE_CONSENT_ASSET_URL=null
      
  2. Cookie Prefix Conflicts:

    • Ensure cookie_prefix in the config doesn’t clash with existing cookies (e.g., Laravel’s laravel_session):
      'cookie_prefix' => 'app_',
      
  3. JavaScript Execution Order:

    • Scripts defined in js_action run after the consent modal is dismissed. Avoid relying on them for critical page functionality.
  4. RTL Layout Quirks:

    • Test RTL layouts thoroughly. Some layouts (e.g., bar-inline) may require manual adjustments for button alignment.
  5. Caching Issues:

    • Clear view and config caches after publishing updates:
      php artisan view:clear
      php artisan config:clear
      

Debugging

  • Check Consent Status: Inspect cookies in browser dev tools (look for {cookie_prefix}_consent). Use Tinker to debug:

    php artisan tinker
    >>> \Devrabiul\CookieConsent\Facades\CookieConsent::getConsent();
    
  • Log Consent Changes: Enable debug mode in the config:

    'debug' => env('COOKIE_CONSENT_DEBUG', false),
    

    This logs consent events to storage/logs/cookie-consent.log.

  • Verify Script Loading: Check the browser console for errors after dismissing the modal. Common issues:

    • Missing js_action functions.
    • Incorrect asset paths (e.g., COOKIE_CONSENT_ASSET_URL misconfigured).

Extension Points

  1. Custom Modal Templates: Override the default Blade template in resources/views/vendor/cookie-consent/modal.blade.php:

    @extends('vendor.cookie-consent::modal')
    @section('custom_content')
        <p>Your custom content here.</p>
    @endsection
    
  2. Dynamic Cookie Categories: Fetch categories from a database:

    'cookie_categories' => CookieCategory::all()->pluck('name')->map(function ($name) {
        return [
            'enabled' => true,
            'locked' => false,
            'title' => __("CookieConsent::{$name}_title"),
        ];
    })->toArray(),
    
  3. Event-Driven Extensions: Listen for consent changes to trigger custom logic:

    CookieConsent::consentChanged(function ($category, $accepted) {
        if ($accepted && $category === 'analytics') {
            Analytics::flushEvents();
        }
    });
    
  4. Headless Mode: Disable the UI but keep consent logic:

    'consent_modal_enabled' => false,
    'consent_banner_enabled' => false,
    

    Useful for APIs or non-interactive contexts.

Pro Tips

  • A/B Testing: Randomize the consent_modal_layout in the config to test different designs:

    'consent_modal_layout' => ['box-wide', 'bar-inline'][rand(0, 1)],
    
  • Conditional Consent: Disable consent for specific routes:

    Route::middleware(['cookie-consent:analytics'])->group(function () {
        // Routes requiring analytics consent
    });
    
  • Localization Fallback: Ensure default translations are published:

    php artisan vendor:publish --tag=cookie-consent-lang --force
    
  • Performance: Lazy-load scripts by setting disable_page_interaction: true to prevent resource-hogging until consent is granted.

  • Compliance Audits: Use the CookieConsent::getAuditLog() method to generate compliance reports:

    $log = CookieConsent::getAuditLog();
    // Export to CSV or database
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai