PHPackages                             leobsst/laravel-cookie-consent - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. leobsst/laravel-cookie-consent

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

leobsst/laravel-cookie-consent
==============================

A cookie consent package for Laravel applications, providing an easy way to manage user consent for cookies in compliance with privacy regulations.

v2.0.24(1mo ago)04.4k↓82.6%[1 PRs](https://github.com/leobsst/laravel-cookie-consent/pulls)MITBladePHP ^8.2CI passing

Since Nov 4Pushed 1w agoCompare

[ Source](https://github.com/leobsst/laravel-cookie-consent)[ Packagist](https://packagist.org/packages/leobsst/laravel-cookie-consent)[ Docs](https://github.com/leobsst/laravel-cookie-consent)[ GitHub Sponsors](https://github.com/LEOBSST)[ RSS](/packages/leobsst-laravel-cookie-consent/feed)WikiDiscussions 2.x Synced 2d ago

READMEChangelog (10)Dependencies (76)Versions (37)Used By (0)

[![Laravel Logo](https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg)](https://laravel.com)

 [![Version](https://camo.githubusercontent.com/4e914e309092d2d9c17520eed9f92bd0d0a6602a73da2000cec3858cb406382c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c656f627373742f6c61726176656c2d636f6f6b69652d636f6e73656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/leobsst/laravel-cookie-consent) [![Laravel](https://camo.githubusercontent.com/2a13c63c764db577df995d8d2c60b7e5df4448a4d7391fc47dea1773ad0e7c0e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d5631312e392532307c2532305631322e782532307c25323031332e782d4646324432303f6c6f676f3d6c61726176656c)](https://laravel.com) [![PHP](https://camo.githubusercontent.com/c4592483be21a67431df3607bb00d9aa91ffb5c78a669a30d52ae5acded2f96a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322b2d3737374242343f6c6f676f3d706870)](https://www.php.net)

 [![Downloads](https://camo.githubusercontent.com/4937d9a0dd041033f265ed79c6f944e97b17f8bf3af079a78c23aad8a4f6713f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c656f627373742f6c61726176656c2d636f6f6b69652d636f6e73656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/leobsst/laravel-cookie-consent) [![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](https://opensource.org/licenses/MIT)

Laravel Cookie Consent
======================

[](#laravel-cookie-consent)

A lightweight Laravel package for handling cookie consent with Google Tag Manager and Google AdSense integration. No Livewire required — the banner is a pure Blade component with vanilla JavaScript, making it usable in any Laravel project.

Features
--------

[](#features)

- Zero Livewire dependency — pure Blade component + vanilla JS
- Simple binary consent system (Accept/Refuse)
- Automatic Google Tag Manager integration with Consent Mode v2
- Google AdSense integration with Consent Mode v2 (without GTM)
- Auto-generated `/ads.txt` endpoint when AdSense is configured
- PostHog analytics integration
- Cookie set client-side (non-HttpOnly, readable by JS)
- Persistent user preferences stored in cookies (1 year by default)
- Tailwind CSS styling with customizable accent color
- Dark mode support
- Multi-language support (EN, FR, IT, ES, DE)

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.9 or 12.x or 13.x
- Tailwind CSS or higher

Installation
------------

[](#installation)

### Step 1: Install the Package

[](#step-1-install-the-package)

```
composer require leobsst/laravel-cookie-consent
```

### Step 2: Publish Assets (Required)

[](#step-2-publish-assets-required)

```
php artisan vendor:publish --tag=cookie-consent-assets
```

This publishes `public/vendor/cookie-consent/cookie-consent.js`, the JavaScript file that handles cookie writing and Google Tag Manager consent updates.

### Step 3: Publish Config File (Recommended)

[](#step-3-publish-config-file-recommended)

```
php artisan vendor:publish --tag=cookie-consent-config
```

This creates `config/cookie-consent.php` where you can customize:

- **GOOGLE\_TAG\_MANAGER\_ID**: Your GTM container ID (e.g. `GTM-XXXXXXX`)
- **GOOGLE\_ADSENSE\_CLIENT\_ID**: Your AdSense publisher ID (e.g. `pub-XXXXXXXXXXXXXXXX`)
- **ENABLE\_AUTOGENERATED\_ADS\_FILE**: Serve an auto-generated `/ads.txt` (default: `true`)
- **POSTHOG\_PROJECT\_TOKEN**: Your PostHog project token
- **POSTHOG\_HOST**: PostHog instance host (default: `https://eu.i.posthog.com`)
- **POSTHOG\_UI\_HOST**: PostHog UI host when using a reverse proxy (default: same as `POSTHOG_HOST`)
- **LEARN\_MORE\_LINK**: URL or route name for the "Learn more" link (default: `/privacy-policy`)
- **CONSENT\_BANNER\_VIEW**: Override the banner view
- **ACCENT\_COLOR**: Button and link color (default: `#3490dc`)
- **duration**: Cookie lifetime in minutes (default: 1 year)
- **same\_site**: SameSite cookie attribute (default: `Lax`)

### Alternative: Use the Install Command

[](#alternative-use-the-install-command)

```
php artisan cookie-consent:install
```

This will publish the config file and assets, then ask you to star the repository on GitHub.

Configuration
-------------

[](#configuration)

### Tailwind CSS Integration

[](#tailwind-css-integration)

Important

Add the following to your `app.css` so Tailwind processes the banner's utility classes:

```
@source '../../../../vendor/leobsst/laravel-cookie-consent/resources/views/**/*.blade.php';
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

1. **Add your Google Tag Manager ID to `.env`:**

```
GOOGLE_TAG_MANAGER_ID=GTM-XXXXXXX
```

2. **Add the scripts directive and the banner component to your layout:**

```

    @cookieConsentScripts

```

The banner automatically appears for users who have not yet set their cookie preferences.

### Complete Example

[](#complete-example)

```

    {{ config('app.name') }}

    @vite(['resources/css/app.css', 'resources/js/app.js'])

    {{-- Google Tag Manager with Consent Mode --}}
    @cookieConsentScripts

        {{ $slot }}

    {{-- Cookie Consent Banner --}}

```

### How It Works

[](#how-it-works)

1. `@cookieConsentScripts` (or ``) injects the GTM snippet with `gtag('consent', 'default', ...)`. The initial state depends on the `cookie_consent` cookie already being set (e.g. returning visitors).
2. `` renders the banner only when GTM is configured **and** the user has not yet made a choice. It also injects a small `window.CookieConsent` config object (cookie name, duration, SameSite, secure flag) and the banner's JavaScript inline.
3. When the user clicks Accept or Refuse, the bundled `cookie-consent.js` script:

    - Writes the `cookie_consent` cookie directly in the browser (non-HttpOnly so it remains readable by JS on subsequent page loads)
    - Calls `gtag('consent', 'update', ...)` to update consent in the current GTM session
    - Hides the banner instantly without a page reload

### Checking User Consent

[](#checking-user-consent)

The `HandleCookieConsent` middleware shares `$cookieConsentStatus` with all views:

```
// In a Blade view
@if($cookieConsentStatus === 'full')
    {{-- User has accepted all cookies --}}
@endif
```

You can also read the cookie directly via the `$_COOKIE` superglobal:

```
$consent = $_COOKIE['cookie_consent'] ?? null;
// 'full'  — accepted
// 'none'  — refused
// null    — not yet set
```

Note

Do **not** use `request()->cookie('cookie_consent')` — Laravel's `EncryptCookies` middleware will try to decrypt the value and return `null`, because the cookie is written as plain text by the browser-side JavaScript. Reading it via `$_COOKIE` bypasses decryption and returns the raw value correctly.

### Customizing the Banner

[](#customizing-the-banner)

Publish the views to modify them:

```
php artisan vendor:publish --tag=cookie-consent-views
```

This copies the views to `resources/views/vendor/cookie-consent/`. You can also point to a completely custom view via the config:

```
// config/cookie-consent.php
'CONSENT_BANNER_VIEW' => 'my-theme.cookie-banner',
```

Your custom view receives these variables from `CookieBanner`:

VariableTypeDescription`$loadScript``bool`Whether GTM is configured`$learnMoreLink``?string`Resolved URL for the "Learn more" link`$accentColor``?string`CSS color value`$cookieDuration``int`Cookie lifetime in **seconds**`$sameSite``string`SameSite attribute value### Translations

[](#translations)

The banner uses the locale set in `config('app.locale')`. Available languages: English (`en`), French (`fr`), Italian (`it`), Spanish (`es`), German (`de`).

To publish and customize translation files:

```
php artisan vendor:publish --tag=cookie-consent-lang
```

Files are published to `resources/lang/vendor/cookie-consent/`.

**Translation keys:**

KeyDefault (EN)`cookie-consent::translations.description`Our website uses cookies...`cookie-consent::translations.question`Do you accept the use of these cookies?`cookie-consent::translations.learn_more`Learn more`cookie-consent::translations.accept`Accept`cookie-consent::translations.refuse`DenyGoogle Tag Manager Consent Mode
-------------------------------

[](#google-tag-manager-consent-mode)

The package implements Google Consent Mode v2.

**Default state (user has not yet decided):**

```
{
  'functional_storage': 'granted',
  'security_storage': 'granted',
  'analytics_storage': 'denied',
  'ad_storage': 'denied',
  'ad_user_data': 'denied',
  'ad_personalization': 'denied'
}
```

**When user accepts:**

```
{
  'functional_storage': 'granted',
  'security_storage': 'granted',
  'analytics_storage': 'granted',
  'ad_storage': 'granted',
  'ad_user_data': 'granted',
  'ad_personalization': 'granted'
}
```

**When user refuses:**

```
{
  'functional_storage': 'granted',
  'security_storage': 'granted',
  'analytics_storage': 'denied',
  'ad_storage': 'denied',
  'ad_user_data': 'denied',
  'ad_personalization': 'denied'
}
```

> **Note:** On a first-time accept, if `gtag` is not yet loaded (GTM script hasn't initialized), the page will reload once so that GTM boots with the correct consent state.

Google AdSense Integration
--------------------------

[](#google-adsense-integration)

If you use Google AdSense **without** Google Tag Manager, the package can inject the AdSense snippet with Consent Mode v2 directly.

### Setup

[](#setup)

1. **Set your publisher ID in `.env`:**

```
GOOGLE_ADSENSE_CLIENT_ID=pub-XXXXXXXXXXXXXXXX
```

2. The package automatically:
    - Adds `` to prevent duplicate consent banners
    - Injects the AdSense `gtag.js` snippet with Consent Mode v2 defaults based on the user's current consent status
    - Serves an auto-generated `/ads.txt` file at your site's root

> **Note:** If `GOOGLE_TAG_MANAGER_ID` is also set, the AdSense snippet is skipped — GTM handles consent signaling instead.

### Auto-generated ads.txt

[](#auto-generated-adstxt)

When `GOOGLE_ADSENSE_CLIENT_ID` is configured and `ENABLE_AUTOGENERATED_ADS_FILE` is `true` (default), the package registers a `/ads.txt` route that returns a plain-text file containing your publisher ID alongside common authorized ad network declarations.

To disable this endpoint:

```
ENABLE_AUTOGENERATED_ADS_FILE=false
```

PostHog Integration
-------------------

[](#posthog-integration)

The package can inject the PostHog analytics snippet directly when `POSTHOG_PROJECT_TOKEN` is set.

### Setup

[](#setup-1)

1. **Set your project token in `.env`:**

```
POSTHOG_PROJECT_TOKEN=phc_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```

2. Optionally override the host (defaults to EU Cloud):

```
POSTHOG_HOST=https://eu.i.posthog.com   # EU Cloud (default)
# POSTHOG_HOST=https://us.i.posthog.com  # US Cloud
# POSTHOG_HOST=https://your-proxy.example.com  # Reverse proxy

# Only needed when POSTHOG_HOST points to a reverse proxy
POSTHOG_UI_HOST=https://eu.posthog.com
```

3. PostHog is initialized unconditionally on every page load. It uses `cookie` persistence so it respects the user's cookie consent state.

> **Note:** PostHog can be combined with GTM or AdSense — all three integrations are independent and stack freely.

Advanced Configuration
----------------------

[](#advanced-configuration)

### Environment Variables

[](#environment-variables)

```
# Google Tag Manager
GOOGLE_TAG_MANAGER_ID=GTM-XXXXXXX

# Google AdSense (optional — enables Consent Mode v2 and auto ads.txt)
GOOGLE_ADSENSE_CLIENT_ID=pub-XXXXXXXXXXXXXXXX
ENABLE_AUTOGENERATED_ADS_FILE=true

# PostHog (optional)
POSTHOG_PROJECT_TOKEN=phc_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
POSTHOG_HOST=https://eu.i.posthog.com
POSTHOG_UI_HOST=https://eu.posthog.com

# Optional
COOKIE_LEARN_MORE_LINK=/privacy-policy
COOKIE_CONSENT_BANNER_VIEW=cookie-consent::components.cookie-banner
COOKIE_CONSENT_ACCENT_COLOR=#3490dc
```

### Resetting a User's Consent

[](#resetting-a-users-consent)

```
use Illuminate\Support\Facades\Cookie;

Cookie::queue(Cookie::forget('cookie_consent'));
```

FAQ
---

[](#faq)

### Does this package require Livewire?

[](#does-this-package-require-livewire)

No. As of v2, Livewire is not required. The banner is a Blade component and all consent logic runs in vanilla JavaScript.

### Can I use this without Google Tag Manager?

[](#can-i-use-this-without-google-tag-manager)

Yes. Simply don't set `GOOGLE_TAG_MANAGER_ID`. If you set `GOOGLE_ADSENSE_CLIENT_ID` instead, the package will inject AdSense with Consent Mode v2. If neither is configured, the banner will not appear, but the `cookie_consent` cookie will still be available for your own scripts.

### How do I style the banner to match my design?

[](#how-do-i-style-the-banner-to-match-my-design)

1. Use `ACCENT_COLOR` in the config to change the button/link color.
2. Publish the views and edit the Tailwind classes.
3. Create a completely custom view and point `CONSENT_BANNER_VIEW` to it.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Security
--------

[](#security)

If you find a security vulnerability, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [LEOBSST](https://github.com/LEOBSST)
- [B.L.A.M. PRODUCTION](https://linksly.fr/BLAM-PRODUCTION)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance95

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 91.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Recently: every ~0 days

Total

34

Last Release

39d ago

Major Versions

1.x-dev → v2.0.02026-03-18

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/46266177?v=4)[LEOBSST](/maintainers/leobsst)[@leobsst](https://github.com/leobsst)

---

Top Contributors

[![leobsst](https://avatars.githubusercontent.com/u/46266177?v=4)](https://github.com/leobsst "leobsst (127 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (9 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

laravellaravel-cookie-consentLEOBSSTBLAM PRODUCTION

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/leobsst-laravel-cookie-consent/health.svg)

```
[![Health](https://phpackages.com/badges/leobsst-laravel-cookie-consent/health.svg)](https://phpackages.com/packages/leobsst-laravel-cookie-consent)
```

###  Alternatives

[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

329530.5k29](/packages/codewithdennis-filament-select-tree)[leandrocfe/filament-apex-charts

Apex Charts integration for Filament PHP.

4911.6M11](/packages/leandrocfe-filament-apex-charts)[filament/support

Core helper methods and foundation code for all Filament packages.

2331.0M245](/packages/filament-support)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.4k](/packages/tomshaw-electricgrid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
