milenmk/laravel-gdpr-cookie-manager

0.6.0-alpha 2025-08-31 08:33 UTC

README

This package is still in development! Do not use in production yet!

Latest Version on Packagist Total Downloads GitHub User's stars Laravel 10 Support PHP Version Support License Contributions Welcome Sponsor me

A comprehensive Laravel package for GDPR-compliant cookie management, featuring automated cookie consent tracking and dynamic cookie injection based on user preferences. Built with both traditional Blade templates and modern Livewire components for maximum flexibility.

✨ Key Features

🍪 Cookie Consent Management

  • GDPR Compliant - Automatic consent tracking with IP addresses, timestamps, and versions
  • Flexible Banner Display - Multiple positions (top, bottom, modal) with customizable messaging
  • Consent Versioning - Re-request consent when cookie policies change
  • User Support - Works with both authenticated users and anonymous visitors

🎛️ Dynamic Cookie Settings & Injection

  • Category Management - Organize cookies into categories (Essential, Analytics, Marketing, etc.)
  • Dynamic Script Injection - Load cookie scripts based on user consent without page reloads
  • Flexible Placement - Configure scripts for <head>, <body>, or footer placement
  • User Control Interface - Granular cookie category management for users

🔧 Technical Features

  • Dual Rendering Modes - Choose between Blade templates or Livewire components
  • Alpine.js Integration - Dynamic interactions without page reloads (Blade mode)
  • Responsive Design - Mobile-first with Tailwind CSS and dark mode support
  • Multi-language Ready - Easy localization support

📋 Requirements

  • PHP 8.2 or higher
  • Laravel 10.x, 11.x, or 12.x
  • Livewire 3.x (optional, only if using Livewire mode)

🚀 Quick Start

1. Installation

composer require milenmk/laravel-gdpr-cookie-manager

2. Publish and Run Migrations

php artisan vendor:publish --tag=gdpr-cookie-manager-migrations
php artisan migrate

3. Publish Configuration

php artisan vendor:publish --tag=gdpr-cookie-manager-config

4. Add to Your Layout

For Blade Mode (Default)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="csrf-token" content="{{ csrf_token() }}" />

        <!-- Package styles -->
        @lgcmStyles

        <!-- Cookie header scripts (Google Analytics, etc.) -->
        @lgcmHeaderCookies
    </head>
    <body>
        <!-- Cookie body scripts (Facebook Pixel, etc.) -->
        @lgcmBodyCookies

        <!-- Your content -->

        <!-- Cookie footer scripts -->
        @lgcmFooterCookies

        <!-- Cookie consent banner and settings -->
        @lgcmContent
    </body>
</html>

For Livewire Mode

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="csrf-token" content="{{ csrf_token() }}" />

        <!-- Package styles -->
        @lgcmStyles

        <!-- Cookie header scripts (Google Analytics, etc.) -->
        @lgcmHeaderCookies

        <!-- Livewire styles -->
        @livewireStyles
    </head>
    <body>
        <!-- Cookie body scripts (Facebook Pixel, etc.) -->
        @lgcmBodyCookies

        <!-- Your content -->

        <!-- Cookie footer scripts -->
        @lgcmFooterCookies

        <!-- Cookie consent banner and settings (Livewire) -->
        @lgcmContent

        <!-- Livewire scripts -->
        @livewireScripts
    </body>
</html>

5. Configure Environment

# Basic settings
COOKIE_CONSENT_ENABLED=true
COOKIE_SETTINGS_RENDERING_MODE=blade  # or 'livewire'
COOKIE_SETTINGS_TYPE=modal           # or 'page'
COOKIE_CONSENT_BANNER_POSITION=bottom # or 'top', 'modal'

# Consent versioning (update when policy changes)
COOKIE_CONSENT_VERSION=1.0

6. Optional: Livewire Setup

If you want to use Livewire mode, install Livewire first:

composer require livewire/livewire

Then update your environment:

COOKIE_SETTINGS_RENDERING_MODE=livewire

That's it! The package will now show a consent banner and handle cookie management automatically.

💡 Need more details? Check the complete documentation for advanced configuration, customization options, and implementation guides.

⚙️ Configuration Options

Rendering Modes

Mode Description Best For Requirements
Blade Traditional templates with Alpine.js Simple setups, existing Blade apps Alpine.js (included)
Livewire Modern reactive components Apps already using Livewire Livewire 3.x

Blade Mode Features

  • ✅ Alpine.js for dynamic interactions
  • ✅ Traditional form submissions
  • ✅ Works without additional dependencies
  • ✅ Dynamic script injection without page reloads
  • ✅ Full page and modal settings support

Livewire Mode Features

  • ✅ Real-time reactive updates
  • ✅ No page reloads required
  • ✅ Server-side validation
  • ✅ Automatic state management
  • ✅ Full page and modal settings support
  • ⚠️ Requires Livewire 3.x installation

Settings Display

Type Description User Experience
Modal Popup overlay Quick settings without leaving page
Page Dedicated settings page Detailed cookie management

Banner Positions

Position Description Use Case
Bottom Fixed banner at bottom Non-intrusive, standard approach
Top Fixed banner at top High visibility
Modal Centered overlay Maximum attention

🏗️ Layout Requirements

Default Layout Structure

The package assumes your application uses a standard Laravel layout structure. The cookie settings page uses <x-app-layout> by default.

Custom Layout Configuration

If you're using a different layout structure, you have several options:

Option 1: Publish and Customize Views

php artisan vendor:publish --tag=gdpr-cookie-manager-views

Then edit resources/views/vendor/gdpr-cookie-manager/cookie-settings.blade.php to use your custom layout:

<x-your-custom-layout>
    <x-slot name="header">
        <h2 class="text-xl leading-tight font-semibold text-gray-800 dark:text-gray-200">
            {{ __('Cookie Settings') }}
        </h2>
    </x-slot>

    <!-- Rest of the content -->
</x-your-custom-layout>

Option 2: Livewire Layout Configuration

For Livewire mode, you can configure the layout in your AppServiceProvider:

use Livewire\Livewire;

public function boot()
{
    // Configure Livewire to use your custom layout
    Livewire::setUpdateRoute(function ($handle) {
        return Route::post('/livewire/update', $handle)
            ->middleware(['web', 'your-middleware']);
    });
}

Or modify the Livewire component after publishing views to specify your layout:

return $view->layout('your-custom-layout', [
    'title' => 'Cookie Settings',
]);

Layout Requirements

Your layout should include:

  • CSRF token meta tag
  • Basic responsive viewport meta tag
  • Support for dynamic content sections (header slot, main content)

🎯 Advanced Features

Dynamic Script Injection

Blade Mode

For seamless user experience without page reloads:

<head>
    @lgcmHeaderCookies
    @lgcmScripts
    <!-- Enables dynamic injection -->
</head>

Livewire Mode

Script injection is handled automatically by Livewire components. No additional setup required:

<head>
    @lgcmHeaderCookies
    @livewireStyles
</head>
<body>
    @lgcmBodyCookies
    @lgcmContent
    @livewireScripts
</body>

Cookie Management

use Milenmk\LGCM\Models\Cookie;
use Milenmk\LGCM\Models\CookieCategory;

// Create cookie category
$analytics = CookieCategory::create([
    'name' => 'Analytics',
    'description' => 'Help us understand website usage',
    'enabled' => true,
]);

// Create cookie
Cookie::create([
    'title' => 'Google Analytics',
    'name' => 'google-analytics',
    'description' => 'Tracks website usage and visitor behavior',
    'content' => '<script>/* GA code */</script>',
    'placement' => 'head',
    'cookie_category_id' => $analytics->id,
    'expiration_days' => 730,
]);

Programmatic Access

Service Layer (Both Modes)

use Milenmk\LGCM\Services\CookieConsentService;

$service = app(CookieConsentService::class);

// Check consent status
if ($service->hasConsent()) {
    // User has given consent
}

// Check if banner should show
if ($service->shouldShowBanner()) {
    // Show consent banner
}

Livewire Component Integration

// In your Livewire component
class YourComponent extends Component
{
    public function render()
    {
        return view('your-view')->with('showCookieConsent', app(CookieConsentService::class)->shouldShowBanner());
    }
}

JavaScript Events (Livewire Mode)

// Listen for consent events
document.addEventListener('livewire:init', () => {
    Livewire.on('consentSaved', (event) => {
        console.log('Consent status:', event[0].status);
        // Handle consent change
    });

    Livewire.on('choicesSaved', (event) => {
        console.log('Cookie choices updated:', event[0].choices);
        // Handle cookie choices change
    });
});

📚 Documentation

For detailed documentation, see the /docs folder:

💻 CRUD Examples

Complete CRUD examples for cookie management are available in the /examples folder:

⚠️ Security Warning: The examples are for demonstration only. You MUST implement proper authentication, authorization, and security measures before using in production. See the examples README for detailed security requirements.

🔧 Optional Assets

Publish Views (for customization)

php artisan vendor:publish --tag=gdpr-cookie-manager-views

Publish CSS (for styling customization)

php artisan vendor:publish --tag=gdpr-cookie-manager-assets

🌍 Environment Variables

# Core settings
COOKIE_CONSENT_ENABLED=true
COOKIE_SETTINGS_RENDERING_MODE=blade
COOKIE_SETTINGS_TYPE=modal
COOKIE_CONSENT_BANNER_POSITION=bottom
COOKIE_CONSENT_VERSION=1.0

# Cookie configuration
COOKIE_CONSENT_NAME=cookie_consent_status
COOKIE_CONSENT_LIFETIME=120
COOKIE_CONSENT_SECURE=true
COOKIE_CONSENT_HTTP_ONLY=true
COOKIE_CONSENT_SAME_SITE=lax

# Custom messages
COOKIE_CONSENT_MESSAGE="This website uses cookies to ensure you get the best experience."
COOKIE_CONSENT_AGREE_TEXT="Accept All"
COOKIE_CONSENT_DECLINE_TEXT="Essential Only"
COOKIE_CONSENT_SETTINGS_TEXT="Settings"

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This package is open-sourced software licensed under the MIT license.

💖 Support

If you find this package helpful, please consider: