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

whitecube/laravel-cookie-consent

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require whitecube/laravel-cookie-consent
    

    Publish the service provider, config, and optionally views/translations:

    php artisan vendor:publish --tag=laravel-cookie-consent-service-provider
    php artisan vendor:publish --tag=laravel-cookie-consent-config
    php artisan vendor:publish --tag=laravel-cookie-consent-views --tag=laravel-cookie-consent-lang
    
  2. Register Cookies: Override registerCookies() in app/Providers/CookiesServiceProvider.php:

    protected function registerCookies(): void {
        Cookies::essentials()->session()->csrf();
        Cookies::analytics()->google(id: 'UA-XXXXXX');
    }
    
  3. Add Blade Directives: Include in your layout:

    @cookieconsentscripts
    @cookieconsentview
    

First Use Case

Enable GDPR-compliant cookie consent for a production site with Google Analytics:

// In CookiesServiceProvider
Cookies::analytics()
    ->google(id: config('services.google_analytics.id'), anonymizeIp: true);

Implementation Patterns

Core Workflow

  1. Cookie Registration:

    • Group cookies by category (essentials, analytics, optional, or custom).
    • Define each cookie with name(), description(), and duration().
    • Use shorthand methods for common services (e.g., google() for GA4).
  2. Consent Handling:

    • Server-Side: Check consent via Cookies::consent() or dependency injection.
    • Client-Side: Use @cookieconsentscripts to load JS only after consent.
  3. Dynamic Features:

    • Conditionally load scripts/cookies via accepted() callbacks:
      Cookies::optional()
          ->name('theme')
          ->accepted(fn(Consent $consent) => $consent->script('<script src="/theme.js"></script>'));
      

Integration Tips

  • Analytics: Automatically inject GA scripts only after consent:
    @cookieconsentscripts
    
  • Theming: Toggle features based on consent:
    if (Cookies::consent()->has('optional')) {
        $theme = session('theme');
    }
    
  • Multi-Domain: Use domain() in accepted() to sync consent across subdomains.

Common Patterns

Pattern Example
Essential Cookies Cookies::essentials()->session()->csrf()
Analytics Cookies::analytics()->google(id: 'UA-123')
Custom Cookie Cookies::optional()->name('prefs')->accepted(fn(Consent $c) => $c->cookie('value'))
Conditional JS @cookieconsentscripts (loads only after consent)

Gotchas and Tips

Pitfalls

  1. Missing Service Provider:

    • Error: Class 'Cookies' not found.
    • Fix: Ensure CookiesServiceProvider is registered after RouteServiceProvider in config/app.php.
  2. Consent Not Persisting:

    • Cause: Forgetting to call parent::registerCookies() in custom providers.
    • Fix: Extend the base provider:
      class CookiesServiceProvider extends \Whitecube\LaravelCookieConsent\CookiesServiceProvider {
          protected function registerCookies(): void {
              parent::registerCookies();
              // Custom cookies...
          }
      }
      
  3. GA Scripts Not Loading:

    • Cause: Missing @cookieconsentscripts in <head>.
    • Fix: Add the directive to your layout file.
  4. Translation Keys Missing:

    • Error: Undefined translations for cookie categories.
    • Fix: Publish translations and update config/cookieconsent.php:
      'categories' => [
          'analytics' => [
              'title' => 'Analytics Cookies',
              'description' => 'Track visitor behavior.',
          ],
      ],
      

Debugging Tips

  • Check Consent Status:
    dd(Cookies::consent()->all()); // Returns array of consented categories
    
  • Inspect Cookies: Use browser dev tools to verify cookies like __cookie_consent are set.
  • Log Cookie Definitions: Add debug output in registerCookies() to verify cookie registration:
    \Log::debug('Registered cookies:', Cookies::all());
    

Extension Points

  1. Custom Categories: Extend CookiesCategory for unique logic:

    class MyCategory extends CookiesCategory {
        public function specialCookie() {
            return $this->cookie(fn(Cookie $c) => $c->name('special')->duration(30));
        }
    }
    

    Register via:

    Cookies::category('my-category', fn() => new MyCategory());
    
  2. Override Views: Publish views and modify:

    php artisan vendor:publish --tag=laravel-cookie-consent-views
    

    Customize resources/views/vendor/cookie-consent/modal.blade.php.

  3. Dynamic Consent UI: Use @cookieconsentview with custom data:

    @cookieconsentview(['showDetails' => true])
    

Performance Tips

  • Lazy-Load Scripts: Defer non-essential scripts until consent is given.
  • Cache Consent: Store consent in a session or database for returning users.
  • Minimize Cookies: Use duration(0) for session-only cookies to reduce storage.

Accessibility

  • Keyboard Navigation: Ensure the modal is focusable and closable via Esc.
  • WCAG Compliance: Use semantic HTML and ARIA attributes in custom views.
  • Dark Mode: Test cookie consent UI in dark mode (e.g., for darkmode_enabled cookie).
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.
hamzi/corewatch
minionfactory/raw-hydrator
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