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, views, and 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
    php artisan vendor:publish --tag=laravel-cookie-consent-lang
    
  2. Register the Service Provider:

    • Laravel 9/10: Add to config/app.php after RouteServiceProvider.
    • Laravel 11+: Add to bootstrap/providers.php.
  3. Configure Cookies: Define cookies in App\Providers\CookiesServiceProvider::registerCookies():

    Cookies::essentials()->session()->csrf();
    Cookies::analytics()->google(id: 'UA-XXXXXX');
    Cookies::optional()->name('darkmode')->description('Dark mode preference')->duration(120);
    
  4. Add Blade Directives: Include in your layout:

    @cookieconsentscripts
    @cookieconsentview
    

First Use Case

Display a GDPR-compliant cookie consent modal and enable Google Analytics only after user consent:

Cookies::analytics()->google(id: 'UA-XXXXXX');

Then, in your Blade template:

@cookieconsentscripts
@cookieconsentview

Implementation Patterns

Cookie Registration Workflows

  1. Essential Cookies:

    Cookies::essentials()
        ->session() // Laravel session cookie
        ->csrf();    // XSRF-TOKEN cookie
    
    • Automatically enabled; no consent required.
  2. Analytics Cookies:

    Cookies::analytics()
        ->google(id: 'UA-XXXXXX', anonymizeIp: true);
    
    • Automatically injects Google Analytics script only after consent.
  3. Custom Cookies:

    Cookies::optional()
        ->name('user_prefs')
        ->description('Stores user interface preferences')
        ->duration(30)
        ->accepted(fn(Consent $consent) => $consent->cookie(value: 'dark'));
    
  4. Custom Categories:

    Cookies::category('marketing')
        ->name('ad_tracking')
        ->description('Tracks ad performance')
        ->duration(90);
    

Integration Tips

  • Conditional Script Loading: Use @cookieconsentscripts to load third-party scripts (e.g., Google Tag Manager) only after consent.

    @cookieconsentscripts
    
  • Dynamic Cookie Values: Pass dependencies to the accepted callback:

    $cookie->accepted(fn(Consent $consent, MyService $service) =>
        $consent->cookie(value: $service->getValue())
    );
    
  • Multi-Domain Support: Configure domain in config/cookieconsent.php:

    'domain' => '.yourdomain.com',
    
  • Blade Directives:

    • @cookieconsentview: Renders the consent modal.
    • @cookieconsentscripts: Injects consent-required scripts.

Gotchas and Tips

Pitfalls

  1. Missing Service Provider Registration:

    • Symptom: Cookies not registered or consent modal not appearing.
    • Fix: Ensure CookiesServiceProvider is added after RouteServiceProvider in config/app.php.
  2. Environment-Specific Cookies:

    • Gotcha: Cookies registered in registerCookies() may not load in non-production environments.
    • Fix: Wrap registration in environment checks:
      if (app()->environment('production')) { ... }
      
  3. Translation Keys Missing:

    • Symptom: Modal displays raw keys (e.g., cookieConsent::cookies.categories.analytics).
    • Fix: Publish translations and update resources/lang/{locale}/cookie-consent.php:
      'categories' => [
          'analytics' => [
              'title' => 'Analytics Cookies',
              'description' => 'Track visitor behavior.',
          ],
      ],
      
  4. Script Injection Timing:

    • Gotcha: Third-party scripts (e.g., Google Analytics) may load before consent.
    • Fix: Always use @cookieconsentscripts in the <head> after consent logic.

Debugging

  • Check Consent Status: Use the Cookies facade to debug:

    dd(Cookies::consent()->getConsent());
    

    Returns an array of consented categories (e.g., ['analytics' => true]).

  • Clear Consent Cookie: Manually delete the _cc cookie (or use Tinker):

    \Cookie::queue(Cookie::forget('_cc'));
    

Extension Points

  1. Custom Modal Logic: Override the default view (resources/views/vendor/cookie-consent/modal.blade.php) to modify behavior (e.g., pre-select categories).

  2. Dynamic Cookie Values: Use the accepted callback to fetch real-time data:

    $cookie->accepted(fn(Consent $consent) =>
        $consent->cookie(value: auth()->user()->preferences)
    );
    
  3. API-Only Consent: Disable the modal for API routes by checking the request type:

    if (request()->wantsJson()) {
        return response()->json(['consent' => Cookies::consent()->getConsent()]);
    }
    
  4. Localization: Extend translations for custom categories:

    'categories' => [
        'my-custom' => [
            'title' => 'Custom Cookies',
            'description' => 'My custom description.',
        ],
    ],
    

Performance Tips

  • Lazy-Load Scripts: Defer non-critical scripts (e.g., analytics) until after consent to improve initial load time.

    @cookieconsentscripts(defer)
    
  • Cache Consent Data: Store consent status in the database for logged-in users to avoid cookie checks on every request:

    if (auth()->check()) {
        $consent = User::find(auth()->id())->cookie_consent;
    } else {
        $consent = Cookies::consent()->getConsent();
    }
    
  • Minimize Cookie Count: Group related cookies into categories to reduce modal complexity. Example:

    Cookies::optional()
        ->name('theme')
        ->description('UI theme preference')
        ->duration(365)
        ->accepted(fn(Consent $consent) => $consent->cookie(value: 'light'));
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony