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

Livewire Cookie Consent Laravel Package

martinschenk/livewire-cookie-consent

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require martinschenk/livewire-cookie-consent
    

    Publish the config and views:

    php artisan vendor:publish --provider="Martinschenk\LivewireCookieConsent\CookieConsentServiceProvider"
    
  2. Configuration Edit config/cookie-consent.php to define:

    • Cookie name, expiry, and domains.
    • Default consent state (e.g., false for opt-in).
    • Customize modal text, buttons, and styling.
  3. First Use Case Add the Livewire component to your layout (e.g., resources/views/layouts/app.blade.php):

    @livewire('cookie-consent::cookie-consent')
    

    Ensure the component renders before any scripts (e.g., Google Analytics) that require consent.


Implementation Patterns

Core Workflow

  1. Initialization The component auto-detects if a user has consented via the cookie. If not, it renders the modal.

  2. Consent Handling

    • Opt-in: User clicks "Accept" → cookie is set, modal closes.
    • Opt-out: User clicks "Reject" → cookie is set to false, modal closes.
    • Customize: User clicks "Customize" → opens a detailed preferences modal (if configured).
  3. Integration with Analytics Use the cookie-consent directive in Blade to conditionally load scripts:

    @cookieConsent('analytics')
    <script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
    @endCookieConsent
    

    Or in JavaScript:

    if (window.cookieConsent) {
        window.cookieConsent.loadScript('https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID');
    }
    
  4. Livewire Integration Access consent status in Livewire components:

    use Martinschenk\LivewireCookieConsent\Facades\CookieConsent;
    
    public function someMethod() {
        $hasConsent = CookieConsent::hasConsent();
        // Logic based on consent
    }
    

Advanced Patterns

  • Dynamic Modal Content Override the default modal by publishing views:

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

    Then customize resources/views/vendor/cookie-consent/modal.blade.php.

  • Multi-Language Support Use Laravel’s localization system to translate modal text. Extend the config:

    'messages' => [
        'accept' => __('cookie_consent.accept'),
        'reject' => __('cookie_consent.reject'),
        // ...
    ],
    
  • Conditional Rendering Disable the modal for specific routes or user roles:

    // In your Livewire component
    public function mount() {
        $this->showModal = !auth()->check() || !CookieConsent::hasConsent();
    }
    

Gotchas and Tips

Pitfalls

  1. Cookie Domain Mismatch

    • If cookies aren’t persisting across subdomains, ensure the domain in config/cookie-consent.php matches your setup (e.g., .yourdomain.com).
    • Fix: Set domain: env('APP_URL') or hardcode the correct domain.
  2. Script Loading Race Conditions

    • If scripts load before the consent cookie is set, they may execute prematurely.
    • Fix: Use @cookieConsent directives or dynamically inject scripts via JavaScript:
      document.addEventListener('DOMContentLoaded', function() {
          if (window.cookieConsent && window.cookieConsent.hasConsent('analytics')) {
              var script = document.createElement('script');
              script.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID';
              document.body.appendChild(script);
          }
      });
      
  3. Cached Modal State

    • Browsers or CDNs may cache the initial page load, showing the modal even after consent.
    • Fix: Add a cache-buster query string to the Livewire component:
      @livewire('cookie-consent::cookie-consent', key(['consent', rand()]))
      
  4. Jetstream/Livewire Auth Conflicts

    • If using Jetstream, ensure the cookie consent middleware doesn’t interfere with auth flows.
    • Fix: Exclude auth routes from cookie consent checks in the middleware:
      public function handle($request, Closure $next) {
          if (!$request->routeIs('login', 'register') && !CookieConsent::hasConsent()) {
              return redirect()->route('home');
          }
          return $next($request);
      }
      

Debugging Tips

  • Check Cookie Existence Inspect browser cookies for _cookie_consent. If missing, verify:

    • The Livewire component is rendered.
    • The cookie name in config matches the one being set.
  • Log Consent Status Add a temporary Livewire component to debug:

    public function render() {
        return view('livewire.debug-consent', [
            'consent' => CookieConsent::hasConsent(),
        ]);
    }
    
  • Clear Old Cookies If testing locally, clear cookies or use incognito mode to avoid stale consent states.

Extension Points

  1. Custom Consent Types Extend the config to support multiple consent categories (e.g., analytics, marketing, stats):

    'categories' => [
        'analytics' => ['google_analytics', 'facebook_pixel'],
        'marketing' => ['mailchimp'],
    ],
    

    Then update the modal to handle per-category consent.

  2. Database-Backed Consent Store consent in the database for user accounts:

    // In a User model observer
    public static function boot() {
        static::created(function ($user) {
            $user->cookieConsent = CookieConsent::hasConsent();
            $user->save();
        });
    }
    
  3. Server-Side Consent Checks Create a middleware to block non-compliant requests:

    public function handle($request, Closure $next) {
        if (!$request->hasCookie('_cookie_consent') || !$request->cookie('_cookie_consent')) {
            abort(403, 'Cookie consent required.');
        }
        return $next($request);
    }
    

Configuration Quirks

  • Default Consent Value Setting default_consent: true will auto-accept cookies for all users. Use sparingly for compliance.

  • Secure Cookies If using HTTPS, ensure secure: true in the config to prevent cookie theft over HTTP.

  • SameSite Attribute For modern browsers, add 'samesite' => 'lax' to the cookie config to mitigate CSRF risks.

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