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

spatie/laravel-cookie-consent

Add a simple, customizable cookie consent banner to Laravel. Shows on first visit, stores consent, then stays hidden. No “decline” option, no tracker blocking, and no consent categories—use other tools if you need advanced compliance features.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-cookie-consent
    

    The package auto-registers. No additional steps required unless customization is needed.

  2. First Use Case: Add the consent banner to your layout (e.g., resources/views/layouts/app.blade.php):

    @include('cookie-consent::index')
    

    This renders a Tailwind-styled banner at the bottom of the page.

  3. Verify Functionality:

    • Refresh the page: Banner appears.
    • Click "Allow cookies": Banner disappears, cookie (laravel_cookie_consent) is set for 20 years (configurable).

Key Configuration

Publish the config file (optional, defaults are sufficient for most cases):

php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-config"

Modify config/cookie-consent.php to adjust:

  • enabled (toggle globally)
  • cookie_name (customize cookie name)
  • cookie_lifetime (e.g., 7 for 7 days)

Quick Integration Checklist

Task Command/Action
Install package composer require spatie/laravel-cookie-consent
Add banner to layout @include('cookie-consent::index')
Customize text/translations Publish lang files (--tag="cookie-consent-translations")
Disable for specific routes Use middleware exclusion (see below)

Implementation Patterns

Core Workflows

1. View-Based Integration

  • Pattern: Include the banner in your master layout (e.g., app.blade.php).
  • Pros: Simple, no middleware overhead.
  • Example:
    @include('cookie-consent::index')
    
  • Customization: Override views (resources/views/vendor/cookie-consent/dialogContents.blade.php) for full control.

2. Middleware-Based Integration

  • Pattern: Use CookieConsentMiddleware to auto-insert the banner before the closing </body> tag.
  • Pros: Centralized control, no manual view inclusion.
  • Setup:
    • Laravel 11+: Add to bootstrap/app.php:
      ->withMiddleware(function (Middleware $middleware) {
          $middleware->append(\Spatie\CookieConsent\CookieConsentMiddleware::class);
      })
      
    • Laravel 9/10: Add to app/Http/Kernel.php:
      protected $middleware = [
          // ...
          \Spatie\CookieConsent\CookieConsentMiddleware::class,
      ];
      
  • Exclusion: Skip middleware for admin routes:
    protected $routeMiddleware = [
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'cookie.consent.exclude' => \Spatie\CookieConsent\CookieConsentMiddleware::class,
    ];
    
    Route::middleware(['auth', 'cookie.consent.exclude'])->group(function () {
        // Admin routes
    });
    

3. Conditional Rendering

  • Pattern: Check consent status in Blade templates.
  • Example:
    @if (!cookie()->has('laravel_cookie_consent'))
        @include('cookie-consent::index')
    @endif
    
  • Use Case: Hide banner for logged-in users or specific locales.

Advanced Patterns

Dynamic Cookie Consent Logic

Extend the package to handle multi-category consent (e.g., "Necessary" vs. "Analytics"):

  1. Custom Cookie Handler:
    // app/Services/CookieConsentService.php
    use Spatie\CookieConsent\CookieConsent;
    
    class CookieConsentService extends CookieConsent {
        public function setConsent($categories = []) {
            $cookieValue = json_encode($categories);
            cookie()->queue($this->getCookieName(), $cookieValue, $this->getCookieLifetime());
        }
    }
    
  2. Update Middleware:
    // app/Http/Middleware/CookieConsentMiddleware.php
    public function handle($request, Closure $next) {
        if (!$request->hasCookie($this->cookieName)) {
            // Render custom view with category options
        }
        return $next($request);
    }
    

Localization

  • Pattern: Publish translations and extend for new locales.
    php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-translations"
    
  • Add New Locale (e.g., es):
    // resources/lang/vendor/cookie-consent/es/texts.php
    return [
        'message' => 'Este sitio web utiliza cookies.',
        'agree' => 'Aceptar cookies',
    ];
    

Styling

  • Pattern: Override default Tailwind styles.
    /* resources/css/cookie-consent.css */
    .js-cookie-consent {
        @apply bg-blue-900 text-white p-4 rounded-lg shadow-lg;
    }
    
  • Floating Banner:
    .js-cookie-consent {
        @apply fixed bottom-4 right-4 max-w-md;
    }
    

Integration Tips

With Frontend Frameworks

  • Vue/React: Use middleware to inject the banner into the root component’s template.
    // Example: Vue 3 + Laravel
    app.component('CookieConsent', {
        template: '<div>@include("cookie-consent::index")</div>'
    });
    
  • Alpine.js: Dynamically toggle visibility:
    <div x-data="{ show: !cookie.has('laravel_cookie_consent') }" x-show="show">
        @include('cookie-consent::index')
    </div>
    

With Filament Admin

  • Pattern: Exclude admin routes from the banner.
    // app/Providers/Filament/AdminPanelProvider.php
    public function panel(Panel $panel): Panel {
        return $panel
            ->middleware([
                'web',
                \Spatie\CookieConsent\CookieConsentMiddleware::class,
            ])
            ->exceptMiddleware([
                \Spatie\CookieConsent\CookieConsentMiddleware::class,
            ]);
    }
    

Testing

  • Unit Test Consent Logic:
    use Spatie\CookieConsent\CookieConsent;
    
    public function test_consent_cookie_is_set() {
        $consent = new CookieConsent();
        $response = $this->get('/');
        $response->assertSee('Allow cookies');
        $this->assertTrue($response->getCookie('laravel_cookie_consent'));
    }
    
  • Feature Test:
    public function test_consent_banner_disappears_after_accept() {
        $this->get('/')
             ->assertSee('Please be informed that this site uses cookies');
        $this->post('/cookie-consent', ['accept' => true]);
        $this->get('/')->assertDontSee('Please be informed');
    }
    

Gotchas and Tips

Pitfalls

1. Cookie Domain Mismatch

  • Issue: Banner appears on every page load due to incorrect SESSION_DOMAIN.
  • Fix: Set SESSION_DOMAIN in .env:
    SESSION_DOMAIN=.yourdomain.com
    
  • Debug: Check cookie domain with:
    dd(request()->getCookieJar()->get('laravel_cookie_consent'));
    

2. Middleware Conflicts

  • Issue: Banner appears on API routes or admin panels unintentionally.
  • Fix: Exclude routes via middleware groups or route-specific middleware:
    Route::middleware(['auth', 'cookie.consent.exclude'])->group(function () {
        // Admin routes
    });
    

3. Caching Issues

  • Issue: Banner persists after acceptance due to aggressive caching.
  • Fix: Clear browser cache or test in incognito mode. Ensure cookie_lifetime is reasonable (e.g., 7 days for testing).

4. JavaScript Dependency

  • Issue: Banner fails to hide after clicking "Allow cookies" in non-JS environments.
  • Fix: Ensure the banner includes a fallback (e.g., server-side check):
    @if (!cookie()->has('laravel_cookie_consent'))
        @include('cookie-consent::index')
    @endif
    

Debugging Tips

1. Verify Cookie Settings

  • Check if the cookie is set:
    dd(request()->cookie('laravel_cookie_consent'));
    
  • Inspect cookie attributes in browser dev tools (Application > Cookies).

2. Log Middleware Execution

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