Looking to hire Laravel developers? Try LaraJobs

laravel-consent maintained by ruvelo

Description
A simple cookie-consent banner for Laravel that drives Google Consent Mode v2: accept, reject or choose, stored in a first-party cookie.
Last update
2026/12/04 00:54 (dev-main)
License
Downloads
1

Comments
comments powered by Disqus

Laravel Consent

A simple cookie banner for your Laravel app that drives Google Consent Mode v2: Accept all, Reject all or Choose, stored in a first-party cookie.

Quick start

composer require ruvelo/laravel-consent

Add two tags to your layout: the head component before any Google tag, and the banner right after <body>:

<head>
    <x-consent::head />
    {{-- your Google tag (gtag.js) or Tag Manager snippet, unchanged --}}
</head>
<body>
    <x-consent::banner />
    ...
</body>

That's it. Visitors see the banner until they choose; Google tags wait for their answer, and get it straight away on every later page.

What you get

  • A banner with Accept all, Reject all and Choose, all three equally prominent, as the GDPR guidance from the CNIL and ICO asks.
  • A "Choose" dialog with one switch per category: necessary (always on), analytics, marketing and preferences. Make the list your own in the config.
  • Google Consent Mode v2 wired in: everything denied until the visitor says yes, then updated to match their choice.
  • The choice kept in a first-party cookie for 180 days. Bump one version number after a policy change and everyone is asked again.
  • @consent('analytics') … @endconsent and consent()->allows('analytics') to load other scripts only when allowed.
  • A Cookie settings link for your footer, to change one's mind later.
  • English, French, Spanish and German; every string translatable.
  • Accessible (keyboard, focus kept in the dialog, labelled controls), light and dark, themable with CSS variables, no Tailwind needed, and nothing loaded from anywhere else.
  • Nothing stored on your server, and the same HTML for every visitor, so cached pages keep working.

Optional features

All are off by default.

Respect Global Privacy Control

Browsers that send the Global Privacy Control signal get marketing off, and locked off in the dialog. Set CONSENT_GPC=true. Details.

An event for every choice

Each choice is posted to your app and fires Ruvelo\Consent\Events\ConsentGiven, to sync it with a CRM or your own records. Set CONSENT_RECORD=true. Details.

Proof of consent

Each choice is also stored in a consent_records table: an anonymous id, the policy version, what was allowed and denied, when, and the user when signed in. Set CONSENT_LOG=true and run php artisan migrate. Details.

Using it

The layout

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <x-consent::head />

    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
    <script>
        gtag('js', new Date());
        gtag('config', 'G-XXXXXXX');
    </script>
</head>
<body>
    <x-consent::banner />

    @yield('content')

    <footer>
        <a href="/privacy">Privacy</a>
        <x-consent::settings />
    </footer>
</body>
</html>
  • <x-consent::head /> must come before any Google tag. It defines dataLayer and gtag, sets the Consent Mode defaults, and replays a returning visitor's choice. Tag Manager works the same way: put the GTM snippet after it.
  • <x-consent::banner /> goes once per page, ideally right after <body> so keyboard and screen reader users meet it first. It's rendered hidden, and its script shows it to visitors who haven't chosen yet. Without JavaScript nothing that needs consent can run, so it stays hidden. Pass policy-url="/cookies" (or set CONSENT_POLICY_URL) to link your cookie policy.
  • <x-consent::settings /> is a "Cookie settings" button that reopens the dialog. Give it classes or your own text: <x-consent::settings class="footer-link">Manage cookies</x-consent::settings>. Any element with a data-consent-open attribute does the same, and so does Consent.open() in JavaScript.

Using a Content Security Policy? Pass the nonce: <x-consent::head nonce="..." />. Laravel's Vite nonce (Vite::useCspNonce()) is picked up on its own.

Google Consent Mode v2

The head component sets every consent type to denied before any tag runs, except the ones a required category grants, and asks Google tags to wait 500 ms for an update:

gtag('consent', 'default', {
  security_storage: 'granted',
  analytics_storage: 'denied',
  ad_storage: 'denied',
  ad_user_data: 'denied',
  ad_personalization: 'denied',
  functionality_storage: 'denied',
  personalization_storage: 'denied',
  wait_for_update: 500
});
gtag('set', 'ads_data_redaction', true);

When the visitor chooses, and on every later page for a returning visitor, it calls gtag('consent', 'update', {...}) with each type granted or denied according to the categories:

Category Consent Mode types it grants
necessary (always on) security_storage
analytics analytics_storage
marketing ad_storage, ad_user_data, ad_personalization
preferences functionality_storage, personalization_storage

The type names, the order (default before any tag, then update) and wait_for_update, ads_data_redaction and url_passthrough follow Google's documentation: Consent mode overview and Set up consent mode on websites. ad_user_data and ad_personalization are the two types Consent Mode v2 added. A category can grant any of the seven types; anything else is refused with a clear error, so a typo can't silently leave a type denied.

Your Google tags load as usual: Consent Mode decides what they may store and send. Don't wrap them in @consent.

Loading other scripts only with consent

For tools that don't understand Consent Mode, render them only when allowed:

@consent('analytics')
    <script defer src="https://plausible.io/js/script.js" data-domain="example.com"></script>
@else
    {{-- optional --}}
@endconsent

@unlessconsent('marketing') … @endconsent works too. In PHP:

if (consent()->allows('marketing')) {
    // ...
}

@consent reads the visitor's cookie, so the page differs per visitor, and the script only appears on the next page after they accept. For scripts that should run the moment the visitor accepts, or on pages served from a full-page cache, mark them up in the browser instead:

<script type="text/plain" data-consent="marketing" src="https://connect.facebook.net/en_US/fbevents.js"></script>
<script type="text/plain" data-consent="analytics">
    startMyAnalytics();
</script>

They stay inert until their category is allowed, then run once. Scripts that already ran can't be unloaded: if someone withdraws consent, it applies from the next page.

Categories

The defaults are in config/consent.php. Rename, remove or add categories; the dialog lists them in order:

'categories' => [
    'necessary' => ['required' => true, 'consent_mode' => ['security_storage']],
    'analytics' => ['consent_mode' => ['analytics_storage']],
    'videos' => [
        'label' => 'Embedded videos',
        'description' => 'YouTube and Vimeo players, which set their own cookies.',
        'consent_mode' => [],
    ],
],

Labels and descriptions come from the translations (consent::consent.categories.<key>.label and .description), or the label and description keys above.

Asking again after a policy change

Every choice is stored with consent.version. Change it (CONSENT_VERSION=2) and choices made under the old version no longer count: everyone sees the banner again. Choices also expire after consent.cookie.days (180, following the CNIL's six-month recommendation).

The cookie

cookie_consent, first-party, Path=/, SameSite=Lax, Secure on HTTPS, written by the banner's script. It holds the version, the categories switched on, when, and a random id, for example 1|analytics,preferences|1764806400|3f2a…. It's the one cookie the banner needs, so it's strictly necessary. Laravel's cookie encryption skips it, so pages served from a cache, or read by your own JavaScript, still work. Set CONSENT_COOKIE_DOMAIN=.example.com to share one choice across subdomains.

Global Privacy Control

With CONSENT_GPC=true, a browser sending the GPC signal (the Sec-GPC: 1 header, or navigator.globalPrivacyControl in the page) gets the categories in consent.gpc.categories (marketing) turned off: "Accept all" leaves them off, the dialog shows them switched off and locked with a short explanation, and consent()->allows('marketing') is false even with an older cookie that says yes.

Recording choices

By default the choice never leaves the browser. Set CONSENT_RECORD=true and the banner posts every choice (including "Reject all") to POST /consent, which fires ConsentGiven:

use Ruvelo\Consent\Events\ConsentGiven;

Event::listen(function (ConsentGiven $event) {
    $event->consentId;  // the random id from the cookie
    $event->version;    // '1'
    $event->allowed;    // ['necessary', 'analytics']
    $event->denied;     // ['marketing', 'preferences']
    $event->user;       // the signed-in user, or null
});

For proof of consent, set CONSENT_LOG=true as well and run php artisan migrate. Each choice becomes a row in consent_records (Ruvelo\Consent\Models\ConsentRecord) with the id, version, allowed and denied categories, the user's id when signed in, and the time. The IP address is only stored if you set consent.log.ip_address to true. The id is also in the visitor's cookie, so you can find their records.

The request carries Laravel's CSRF token and is rate limited (throttle:30,1).

Making it look like your app

The banner uses the Ruvelo house style with plain CSS scoped to .consent, follows the visitor's light or dark setting (and data-theme="dark" or a dark class on <html>), and is themed with CSS variables. Override any of them in your own CSS:

.consent { --consent-accent: #0e7c66; --consent-accent-ink: #0a5d4c; --consent-font: inherit; }

The variables are --consent-bg, -subtle, -line, -ink, -text-2, -accent, -accent-ink, -accent-soft, -on-accent, -switch-off, -radius, -radius-lg, -font and -z (the stacking order). For full control, publish the views to resources/views/vendor/consent:

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

Keep "Accept all" and "Reject all" equally easy to see and use: that's what regulators check first.

Accessibility

  • The banner is a labelled region; it doesn't steal focus or block the page.
  • "Choose" opens a native modal <dialog>: the page behind is inert, focus moves into it and stays there (Tab and Shift+Tab wrap), Escape closes it, and focus returns to the button that opened it.
  • Every switch is a real checkbox with a label and a description; required ones are checked and disabled, marked "Always on".
  • Buttons are at least 44px tall, focus is always visible, and animations respect reduced motion.

Translations

English, French, Spanish and German ship with the package, and follow the app's locale. To change a string, or add a language, publish them to lang/vendor/consent:

php artisan vendor:publish --tag=consent-translations

For developers

PHP API

consent() (or app(Ruvelo\Consent\Consent::class)) reads the current request's cookie:

consent()->allows('analytics');   // required categories: always true
consent()->denies('marketing');
consent()->allowed();             // ['necessary', 'analytics']
consent()->hasChoice();           // false until they choose under the current version
consent()->state();               // ConsentState: version, categories, givenAt, id; or null
consent()->gpc();                 // the request carries GPC and the site respects it
consent()->categories();          // the configured categories, with labels
consent()->consentModeFor(['necessary', 'analytics']); // ['analytics_storage' => 'granted', ...]

JavaScript API

The head component (or the banner) defines window.Consent:

Consent.allows('analytics');
Consent.hasChoice();
Consent.acceptAll();
Consent.rejectAll();
Consent.save(['analytics', 'preferences']);
Consent.open();                   // reopen the dialog

document.addEventListener('consent:change', (event) => {
    event.detail.categories;      // ['necessary', 'analytics', 'preferences']
});

Events

Ruvelo\Consent\Events\ConsentGiven (consentId, version, allowed, denied, user), only with recording on.

Exceptions

All extend Ruvelo\Consent\Exceptions\ConsentException: UnknownCategory (asking about a category that isn't configured, usually a typo) and InvalidConfiguration (an unusable version, category key or Consent Mode type).

In your tests

Send the cookie with the request, unencrypted:

$this->withUnencryptedCookie('cookie_consent', '1|analytics|'.time().'|test')
    ->get('/')
    ->assertSee('plausible.io');

Using an AI coding agent?

The package ships Laravel Boost guidelines in resources/boost/guidelines/core.blade.php. With Boost installed (composer require laravel/boost --dev), run php artisan boost:install and pick ruvelo/laravel-consent from the third-party packages (or php artisan boost:update --discover if Boost is already set up). Your agent then knows where the two tags go, how categories map to Consent Mode, and how to load scripts only with consent.

Requirements

Laravel PHP Tested in CI
12 (12.4.1+) 8.3, 8.4, 8.5 yes
13 8.3, 8.4, 8.5 yes
  • Optional, for the proof-of-consent log: a database and php artisan migrate

This package gives you the tools; whether your banner, categories and policy meet the law where you operate is yours to check.

Configuration reference

Publish the config file to change the defaults:

php artisan vendor:publish --tag=consent-config
Key Default
version 1 (CONSENT_VERSION) Stored with each choice. Change it to ask everyone again
categories necessary, analytics, marketing, preferences Key ⇒ required, consent_mode (Consent Mode types it grants), optional label and description
consent_mode.enabled true (CONSENT_MODE) Set to false to use the banner without Google Consent Mode
consent_mode.wait_for_update 500 Milliseconds Google tags wait for the visitor's choice
consent_mode.ads_data_redaction true Redact ad click identifiers while ad_storage is denied
consent_mode.url_passthrough false Pass ad click and session details through URLs while storage is denied
cookie.name cookie_consent (CONSENT_COOKIE)
cookie.days 180 How long a choice lasts
cookie.domain null (CONSENT_COOKIE_DOMAIN) .example.com to share the choice across subdomains
cookie.same_site Lax
policy_url null (CONSENT_POLICY_URL) Linked from the banner and the dialog
gpc.enabled false (CONSENT_GPC) Respect Global Privacy Control
gpc.categories ['marketing'] What GPC turns off
record false (CONSENT_RECORD) Post each choice to the server and fire ConsentGiven
log.enabled false (CONSENT_LOG) Also store each choice in a table (implies record)
log.table consent_records
log.ip_address false Store the visitor's IP address with each record
route.path / .middleware consent / ['web', 'throttle:30,1'] Where choices are posted, when recording

record and log.enabled decide at boot whether the route and migration are registered: set them in .env or the config file, not at runtime.

Upgrading

First release: nothing to upgrade yet. Future upgrade notes go here.

Contributing

Pull requests are welcome. Clone, composer install, then composer check runs code style (Pint), static analysis (PHPStan level 8), the PHP tests and the JavaScript tests, exactly as CI does. See CONTRIBUTING.md and the changelog.

Credits

Built by François Bultez at Valtry, the website security scanner, and everyone who contributes.

License

MIT. See LICENSE.