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

Filament Cookie Consent Laravel Package

jeffersongoncalves/filament-cookie-consent

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require jeffersongoncalves/filament-cookie-consent
    

    Publish the config and migrations:

    php artisan vendor:publish --provider="JeffersonGoncalves\FilamentCookieConsent\FilamentCookieConsentServiceProvider" --tag="config"
    php artisan vendor:publish --provider="JeffersonGoncalves\FilamentCookieConsent\FilamentCookieConsentServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. Register the Widget Add the cookie consent widget to your Filament dashboard layout (e.g., app/Providers/Filament/AdminPanelProvider.php):

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->widgets([
                \JeffersonGoncalves\FilamentCookieConsent\Widgets\CookieConsent::class,
            ]);
    }
    
  3. First Use Case

    • Visit your Filament admin panel. The cookie consent banner will appear automatically for users without consent.
    • Configure cookie categories (e.g., "Analytics," "Marketing") via the Settings page (/admin/cookie-consent/settings).

Implementation Patterns

Core Workflows

  1. Cookie Category Management Define cookie categories in the Filament admin panel under Cookie Consent > Settings:

    // Example: Programmatically add a category (e.g., in a service provider)
    use JeffersonGoncalves\FilamentCookieConsent\Models\CookieCategory;
    
    CookieCategory::create([
        'name' => 'Analytics',
        'description' => 'Track user behavior for analytics',
        'enabled' => true,
        'consent_required' => true,
    ]);
    
  2. Conditional Rendering Check consent status in Blade templates or controllers:

    // Blade
    @if (auth()->check() && auth()->user()->hasCookieConsent())
        <!-- Show content that requires consent -->
    @endif
    
    // Controller
    if ($user->hasCookieConsent('Analytics')) {
        // Load analytics scripts
    }
    
  3. Integration with Frontend Use the hasCookieConsent() helper in JavaScript (via Laravel Mix/Alpine.js):

    document.addEventListener('DOMContentLoaded', () => {
        if (!window.hasCookieConsent('Marketing')) {
            // Disable non-essential scripts
        }
    });
    
  4. Dynamic Banner Customization Override the default banner view by publishing the package views:

    php artisan vendor:publish --provider="JeffersonGoncalves\FilamentCookieConsent\FilamentCookieConsentServiceProvider" --tag="views"
    

    Modify resources/views/vendor/filament-cookie-consent/banner.blade.php.


Advanced Patterns

  1. Automated Consent for Logged-in Users Use a Filament policy to auto-accept consent for admins:

    // app/Policies/CookieConsentPolicy.php
    public function autoAccept(User $user)
    {
        return $user->isAdmin();
    }
    
  2. Third-Party Script Loading Dynamically load scripts based on consent (e.g., Google Analytics):

    // app/Helpers/CookieConsentHelper.php
    public static function loadScripts()
    {
        if (hasCookieConsent('Analytics')) {
            addScript('https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID');
        }
    }
    
  3. Localization Translate cookie messages via Filament’s localization system:

    // config/filament-cookie-consent.php
    'messages' => [
        'accept' => __('cookie_consent.accept'),
        'reject' => __('cookie_consent.reject'),
    ],
    

Gotchas and Tips

Common Pitfalls

  1. Cache Issues

    • Clear Filament cache after updating cookie categories:
      php artisan filament:cache-reset
      
    • Ensure session:store is configured in config/filament.php for persistent consent tracking.
  2. Cookie Domain Mismatch

    • If consent isn’t persisting, verify the domain in config/filament-cookie-consent.php matches your app’s domain (e.g., .example.com for subdomains).
  3. JavaScript Conflicts

    • The banner may not render if loaded after the DOM is ready. Use:
      document.addEventListener('filament:init', () => {
          // Initialize cookie consent logic
      });
      
  4. Migration Errors

    • Run migrations after publishing the config to avoid missing table references.

Debugging Tips

  1. Log Consent Status Add a temporary middleware to log consent checks:

    // app/Http/Middleware/LogCookieConsent.php
    public function handle($request, Closure $next)
    {
        \Log::info('Cookie Consent', [
            'user_id' => auth()->id(),
            'consent' => auth()->user()?->cookieConsent,
        ]);
        return $next($request);
    }
    
  2. Inspect Cookies Use browser dev tools (Application > Cookies) to verify _cookie_consent is set correctly.

  3. Test in Incognito Always test cookie consent in incognito mode to avoid cached consent states.


Extension Points

  1. Custom Consent Logic Extend the CookieConsent model to add custom fields:

    // app/Models/CustomCookieConsent.php
    use JeffersonGoncalves\FilamentCookieConsent\Models\CookieConsent;
    
    class CustomCookieConsent extends CookieConsent
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    
  2. Event Listeners Listen for consent changes to trigger actions (e.g., analytics reset):

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \JeffersonGoncalves\FilamentCookieConsent\Events\ConsentUpdated::class => [
            \App\Listeners\ResetAnalytics::class,
        ],
    ];
    
  3. API Integration Expose consent status via a custom API route:

    // routes/api.php
    Route::get('/cookie-consent', function () {
        return response()->json([
            'consent' => auth()->user()?->cookieConsent,
        ]);
    });
    
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