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

statikbe/laravel-cookie-consent

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require statikbe/laravel-cookie-consent
    

    Publish the config and views:

    php artisan vendor:publish --provider="Statikbe\CookieConsent\CookieConsentServiceProvider" --tag="config"
    php artisan vendor:publish --provider="Statikbe\CookieConsent\CookieConsentServiceProvider" --tag="views"
    
  2. Configuration: Edit config/cookie-consent.php to define:

    • Required cookies (e.g., analytics, marketing).
    • Default consent state (required, optional, or denied).
    • Modal styling (e.g., position, theme).
  3. First Use Case: Add the consent banner to your layout (e.g., resources/views/layouts/app.blade.php):

    @cookieConsent
    

    This injects the modal and handles cookie storage via a cookie_consent session key.


Implementation Patterns

Core Workflow

  1. User Interaction:

    • The modal appears on page load if no consent exists in the session.
    • Users can accept/reject via buttons (e.g., "Accept All," "Reject All," or granular toggles).
    • Consent state persists via a cookie_consent session variable (or cookie, if configured).
  2. Conditional Logic: Use the hasConsent() helper or CookieConsent::check() to gate functionality:

    @if (CookieConsent::check('analytics'))
        <!-- Load Google Analytics -->
        <script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
    @endif
    
  3. Dynamic Cookie Management:

    • Define cookie categories in config/cookie-consent.php:
      'categories' => [
          'analytics' => [
              'purpose' => 'Track user behavior for analytics',
              'default' => 'denied', // or 'optional', 'required'
          ],
          'marketing' => [
              'purpose' => 'Personalized ads',
              'default' => 'denied',
          ],
      ],
      
    • Use CookieConsent::set() to override defaults programmatically:
      CookieConsent::set('analytics', 'accepted');
      
  4. Integration with Frontend:

    • JavaScript Hooks: Trigger custom events when consent changes:
      document.addEventListener('cookieConsentChanged', (e) => {
          console.log('Consent updated:', e.detail);
          // Re-load scripts or update UI
      });
      
    • Blade Directives: Extend the @cookieConsent directive to pass custom data:
      @cookieConsent(['custom' => 'value'])
      
  5. API/SPA Integration:

    • For non-Blade apps, use the CookieConsent::handleRequest() middleware to validate consent on API routes:
      Route::middleware(['cookie.consent:analytics'])->group(function () {
          // Analytics-related API endpoints
      });
      

Gotchas and Tips

Pitfalls

  1. Session vs. Cookie Storage:

    • By default, consent is stored in the session. For persistent storage (e.g., across devices), enable use_cookie in config:
      'use_cookie' => true,
      
    • Warning: Cookies may not reflect real-time changes if the user clears them.
  2. Middleware Conflicts:

    • The CookieConsentMiddleware runs on every request. If you experience performance issues, restrict it to specific routes:
      Route::middleware(['web', 'cookie.consent'])->group(function () {
          // Only apply to web routes
      });
      
  3. Default Consent States:

    • Setting default to 'required' for a category will block page rendering until consent is given. Test this behavior thoroughly in staging.
  4. JavaScript Dependencies:

    • The package relies on jQuery for modal functionality. If your app uses a modern frontend framework (e.g., Vue, React), manually initialize the modal or use a custom view.
  5. Localization:

    • The modal text is hardcoded in English. Override translations by publishing the language files:
      php artisan vendor:publish --provider="Statikbe\CookieConsent\CookieConsentServiceProvider" --tag="lang"
      
    • Edit resources/lang/{locale}/cookie-consent.php.

Debugging Tips

  1. Check Consent State:

    • Inspect the cookie_consent session variable or cookie to verify user choices:
      dd(session('cookie_consent')); // or request()->cookie('cookie_consent')
      
  2. Disable Modal Temporarily:

    • Set 'show_modal' => false in config to bypass the UI while developing.
  3. Log Consent Events:

    • Extend the CookieConsent facade to log changes:
      Statikbe\CookieConsent\Facades\CookieConsent::extend(function ($consent) {
          \Log::info('Consent updated', $consent->getAll());
      });
      

Extension Points

  1. Custom Modal Views:

    • Override the default modal by creating resources/views/vendor/cookie-consent/modal.blade.php.
  2. Additional Consent Categories:

    • Dynamically add categories via a service provider:
      public function boot()
      {
          CookieConsent::addCategory('custom', [
              'purpose' => 'Custom tracking',
              'default' => 'denied',
          ]);
      }
      
  3. Consent API:

    • Expose an API endpoint to update consent via AJAX:
      Route::post('/api/cookie-consent', function (Request $request) {
          $consent = $request->validate(['category' => 'required', 'status' => 'required']);
          CookieConsent::set($consent['category'], $consent['status']);
          return response()->json(['success' => true]);
      });
      
  4. GDPR Compliance:

    • Extend the package to log consent timestamps or integrate with a DSR (Data Subject Request) tool by adding a consent_logs table and middleware to record changes:
      CookieConsent::extend(function ($consent) {
          \App\Models\ConsentLog::create([
              'user_id' => auth()->id(),
              'category' => $consent->getCategory(),
              'status' => $consent->getStatus(),
              'ip' => request()->ip(),
          ]);
      });
      
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