Back to portfolio

Laravel Cookie Consent

Cookie consent for Laravel: banner, script gating and a consent audit trail.

Laravel Cookie Consent — Website preview

Why we wrote this package

The problem: banners that ask but do not wait

A cookie banner is easy to put on a page. The hard part is what happens behind it. On many sites the banner asks the visitor to choose, while the analytics tag, the advertising pixel and the embedded video have already loaded and set their cookies. The question is decorative: the scripts did not wait for the answer.

Consent only means something if non-essential code is held back until the visitor says yes, if the choice can be changed later as easily as it was given, and if you can show afterwards what was agreed to and under which version of the banner. We wanted all three in our own Laravel projects without hand-writing the same glue each time, so we packaged it.

What it wraps and what it adds

The browser side is not ours. The package bundles orestbida/cookieconsent v3 (version 3.3.0 in the current release) and its companion iframemanager (1.3.0). Both are mature, accessible and well documented, and we saw no reason to write another banner. The files are served from your own public/vendor directory, so the banner makes no request to a CDN.

What we added is the Laravel half that a JavaScript library cannot provide:

  • PHP-first configuration. The banner is configured in config/cookieconsent.php, a plain PHP array that reaches CookieConsent.run() almost unchanged. Every upstream option is still available.
  • Translations in Laravel lang files. Banner text lives in lang/vendor/cookieconsent/{locale}/cookieconsent.php and follows app()->getLocale(). The package ships 22 languages.
  • Script gating in Blade. @cookiescript writes a script tag with type="text/plain" and a data-category attribute, so the browser does not execute it until the library enables that category. This is the part that makes the banner more than a question.
  • Consent on the server. @consent, the CookieConsent facade and the consent:* route middleware read the consent cookie during the request, so you can skip rendering markup the visitor has not agreed to, instead of rendering it and hiding it with JavaScript.
  • Click-to-load embeds. @iframe renders an iframemanager placeholder in place of a YouTube or similar embed. The real iframe loads only after the visitor accepts the category you mapped the service to.
  • An audit trail. Every first consent and every later change is posted to a package route and stored as a new row in a consent_logs table, with a hash of the exact configuration the visitor saw.

Decisions visible in the code

The consent cookie is read, not trusted. The library has to read and write cc_cookie in the browser, so the package excludes it from Laravel's EncryptCookies middleware automatically. That makes server-side reads possible, and it also means the visitor can edit the cookie. We document every server-side check as a reflection of the visitor's own stated preference, never as access control.

Consent logs are append-only at the model level. The ConsentLog model throws if you try to update a saved row. Fields used as evidence (IP address, user agent, linked user, policy hash) are filled on the server from the request and never taken from the browser payload. The guard does not stop raw queries; the guide below shows how to close that gap in the database.

The policy hash describes what the visitor actually saw. It is a SHA-256 of the configuration after translations are merged and orphaned sections removed, plus your own policy_version string. When you change the banner, new rows carry a new hash.

Personal data in the log is configurable. You can store the IP address raw, hashed with a salt, or not at all, turn off the user agent, link or not link the authenticated user, and set a retention period that a pruning command enforces.

Logging must not break the banner. The log request never blocks the interface, retries transient failures twice, carries an idempotency key so a retry never creates a duplicate row, and falls back to navigator.sendBeacon() when the tab closes first.

We use the package on core45.com: the banner on this page is rendered by @cookieconsent in our own layout. We describe the wider approach in our article on doing GDPR cookie consent properly in Laravel.

Who it is for, and when it is not the right tool

It is for Laravel 12 and 13 applications that render pages with Blade and want consent handled inside the application: configuration in PHP, text in lang files, records in their own database, and optionally a read-only view of those records in Filament.

It is probably not the right tool if you are not on Laravel, if your front end is a separate single-page application that does not render through Blade (the JavaScript library alone may serve you better), if you need a hosted consent platform with automatic cookie scanning and vendor lists, or if your setup must store consent in localStorage, which makes every server-side check report "no consent".

The package is a technical tool, not legal advice. It helps you implement consent properly, but whether your categories, texts, retention period and records meet the rules that apply to you is a question for your own legal review.

Requirements

  • PHP 8.4 or newer.
  • Laravel 12 or 13 (illuminate/support, illuminate/http and illuminate/database at ^12.0|^13.0).
  • A database for the consent log, which is enabled by default.
  • Optional: Filament v3, v4 or v5 for the read-only consent log resource.

On PHP 8.2 or 8.3, use the ^1.1 line. On Laravel 11, use ^2.0, keeping in mind that Laravel 11 itself no longer receives security fixes.

Installation

  1. Install the package with Composer. The service provider and the CookieConsent facade alias are registered automatically.
  2. Publish the configuration file to config/cookieconsent.php.
  3. Publish the front-end assets. They are copied to public/vendor/cookieconsent and public/vendor/iframemanager.
  4. Run the migrations to create the consent_logs table. The package loads its migration itself, so you do not need to publish it first. If your user model uses UUID, ULID or string keys, set logging.morph_id_type before migrating, because the migration reads it to choose the user_id column type.
composer require core45/laravel-cookieconsent

php artisan vendor:publish --tag=cookieconsent-config
php artisan vendor:publish --tag=cookieconsent-assets
php artisan migrate

Then add @cookieconsent to the <head> of your layout. The banner script waits for DOMContentLoaded internally, so loading it in the head is safe.

<head>
    ...
    @cookieconsent
</head>

You do not need to edit bootstrap/app.php: the consent cookie is added to the EncryptCookies exceptions when the package boots.

Three more tags exist for when you want to customise things:

php artisan vendor:publish --tag=cookieconsent-lang        # lang/vendor/cookieconsent/{locale}/*.php
php artisan vendor:publish --tag=cookieconsent-views       # resources/views/vendor/cookieconsent/*.blade.php
php artisan vendor:publish --tag=cookieconsent-migrations  # copy the migration into database/migrations

Published assets are copies, and composer update does not refresh them. After any release whose changelog says the bundled JavaScript or CSS changed, publish them again:

php artisan vendor:publish --tag=cookieconsent-assets --force

Configuration

Every key in config/cookieconsent.php except translations_mode, translations_override, csp_nonce, defer_assets, logging and iframemanager is passed straight to CookieConsent.run(). Any option from the upstream configuration reference can be added, for example respectGpc or cookie.domain.

KeyDefaultMeaning
cookie.name'cc_cookie'Name of the consent cookie. Server-side reads and the EncryptCookies exception use this value.
cookie.expiresAfterDays182Lifetime of the consent cookie in days.
cookie.useLocalStoragenot set (off)Stores consent in localStorage instead of a cookie. Leave it off if you use any server-side check.
mode'opt-in'Upstream consent mode: 'opt-in' or 'opt-out'.
revision0Upstream configuration revision. Stored with every log row.
guiOptionsbox layout, bottom leftLayout and position of the consent modal and the preferences modal.
categoriesnecessary (read-only), analyticsConsent categories. See below.
translations_mode'active''active' embeds only the current locale; 'all' embeds every available locale.
translations_override'merge''merge' merges published lang files over the package's; 'replace' uses a published file wholesale.
csp_noncenullA callable returning the per-request CSP nonce.
defer_assetsfalseLoads the stylesheet and the library without blocking the first render.
logging.enabledtrueTurns the consent log on or off. When off, no log listeners are rendered and the log route answers 404.
logging.csrftrueSends the CSRF token with log requests. When false, the log route also skips CSRF validation.
logging.capture_ip'raw''raw', 'hashed' (SHA-256 of the IP plus the salt) or false.
logging.ip_hash_saltenv('COOKIECONSENT_IP_SALT')Salt used when capture_ip is 'hashed'.
logging.capture_user_agenttrueStores the user agent, truncated to 1000 characters.
logging.link_usertrueLinks the row to the authenticated user through a polymorphic relation.
logging.morph_id_type'int''int', 'uuid', 'ulid' or 'string'. Must match your user key type; read by the migration.
logging.policy_versionnullYour own policy version string, stored with each row and included in the policy hash.
logging.retention_daysnullAge in days after which cookieconsent:prune deletes rows. null disables pruning.
logging.rate_limit'30,1'Laravel throttle expression applied to the log route.
iframemanager.enabledfalseEnables @iframemanager. When off, the directive renders nothing.
iframemanager.services[]Embed services keyed by name. See "Click-to-load embeds".

Categories are defined under categories using the upstream format. necessary is enabled and read-only; every other category waits for the visitor. autoClear lists the cookies to remove when a category is rejected or withdrawn.

'categories' => [
    'necessary' => ['enabled' => true, 'readOnly' => true],
    'analytics' => [
        'autoClear' => [
            'cookies' => [
                ['name' => '_gid'],
            ],
        ],
    ],
],

Each category needs a section in the preferences modal, which comes from the lang file (preferencesModal.sections, linked by linkedCategory). Sections whose linkedCategory is not a configured category are dropped before the config reaches the browser, so removing analytics from categories also removes its section. The log endpoint only accepts category names that exist in this array.

A plain string in autoClear.cookies[].name is an exact match. For a JavaScript RegExp, use CookieConsent::regex(). The second argument holds the RegExp flags.

use Core45\CookieConsent\Facades\CookieConsent;

'autoClear' => [
    'cookies' => [
        ['name' => CookieConsent::regex('^_ga')],       // matches _ga, _ga_ABC123, ...
        ['name' => CookieConsent::regex('^_gid$', 'i')], // second arg is JS RegExp flags
    ],
],

Blade directives

@cookieconsent

Renders the stylesheet, the library, the configuration, the consent log listeners and the CookieConsent.run() call. Put it once in the <head> of your layout, as shown in the installation steps.

@cookiescript and @endcookiescript

Blocks a script until its category is accepted. The external form takes the category and the URL; the inline form wraps the script body.

@cookiescript('analytics', 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX')

@cookiescript('analytics')
    window.dataLayer = window.dataLayer || [];
    function gtag(){ dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', 'G-XXXXXXX');
@endcookiescript

Prefix the category with ! to run code when consent is absent or withdrawn. A third argument adds HTML attributes, which are escaped.

@cookiescript('!analytics')
    // runs when analytics consent is absent
@endcookiescript

@cookiescript('analytics', 'https://example.com/ga.js', ['data-service' => 'Google Analytics'])

Do not glue @endcookiescript directly onto a word character: Blade will not recognise someCode@endcookiescript as a directive. End the script with ;, } or a newline.

@cookiepreferences

Once answered, the banner does not come back by itself, so visitors need a way to reopen the preferences and change their choice. The directive renders <button type="button" data-cc="show-preferencesModal"> with the consentModal.showPreferencesBtn translation as its label, or Manage preferences if that line is missing.

@cookiepreferences

@cookiepreferences('Cookie settings', ['class' => 'footer__link', 'aria-label' => 'Open cookie settings'])

Attribute values are escaped; true renders a bare attribute and false or null omits it. You cannot override data-cc or type, and inline on* handlers are dropped. Any element with data-cc="show-preferencesModal" works as a trigger too, for example a link in your footer.

Renders its content only if the consent cookie sent with the current request contains the category.

@consent('analytics')
    <p>Analytics-only content.</p>
@endconsent

@iframemanager and @iframe

@iframemanager loads iframemanager and connects it to the consent categories; place it right after @cookieconsent. @iframe renders a placeholder. Both are covered in "Click-to-load embeds" below.

The facade and the Consent class read the same cookie during the request:

use Core45\CookieConsent\Support\Consent;
use Core45\CookieConsent\Facades\CookieConsent;

app(Consent::class)->has('analytics');   // bool
CookieConsent::has('analytics');         // same, via the facade
CookieConsent::categories();             // list<string>, e.g. ['necessary', 'analytics']
CookieConsent::acceptType();             // 'all' | 'necessary' | 'custom' | null (no cookie yet)

The facade also exposes CookieConsent::config(), which returns the array sent to the browser, CookieConsent::policyHash(), which returns the hash stored with log rows, and CookieConsent::regex().

Route middleware

The consent middleware alias takes a category and aborts with 403 when consent for it is missing:

Route::get('/dashboard/analytics', AnalyticsController::class)
    ->middleware('consent:analytics');

Two limits to keep in mind

  • It is not an authorisation boundary. The cookie is unencrypted and the visitor can edit it. Use these checks to respect the visitor's choice, and use policies, gates or server-side state to protect anything sensitive.
  • useLocalStorage turns server-side reads off. With cookie.useLocalStorage set to true, consent never reaches the server: @consent, has() and the middleware always report no consent, and a single Log::warning() is written per PHP process.

In opt-out mode, before the visitor makes a choice, the browser library reports the default-enabled categories as accepted while the server reports no consent, because no cookie exists yet. Check validConsent() in JavaScript if you need to tell "no choice yet" apart.

Click-to-load embeds

Enable iframemanager and describe each service. category names the consent category that unlocks it; a service without one is mapped to necessary. The remaining keys are passed to iframemanager as they are.

'iframemanager' => [
    'enabled' => true,
    'services' => [
        'youtube' => [
            'category' => 'analytics', // which cookieconsent category unlocks this service
            'embedUrl' => 'https://www.youtube-nocookie.com/embed/{data-id}',
            'thumbnailUrl' => 'https://i3.ytimg.com/vi/{data-id}/hqdefault.jpg',
            'iframe' => [
                'allow' => 'accelerometer; autoplay; encrypted-media',
            ],
        ],
    ],
],

Add the directive after @cookieconsent, then put a placeholder where the embed belongs:

@cookieconsent
@iframemanager

@iframe('youtube', $videoId, ['params' => 'rel=0', 'thumbnail' => $customThumbnailUrl])

The options array of @iframe accepts params, thumbnail and ratio, written as data-* attributes, and autoscale, which adds data-autoscale when truthy. The notice and button text come from lang/vendor/cookieconsent/{locale}/iframemanager.php, keyed by service name. The package ships strings for youtube; add a key for every other service you configure.

When the visitor gives consent for the first time (cc:onFirstConsent) or changes it (cc:onChange), the bundled script posts the decision to POST /cookie-consent/log (route name cookieconsent.log). The route runs in the web middleware group with the configured throttle, accepts only application/json (415 otherwise) and rejects bodies over 16 KiB with 413.

ColumnContents
consent_id, revisionThe library's consent identifier and the configuration revision.
actionfirst_consent or change.
accept_typeall, custom or necessary.
accepted_categories, rejected_categories, accepted_servicesJSON arrays.
language_codeThe banner language at the time of consent.
policy_version, policy_hashYour configured version string and the SHA-256 of the effective configuration.
ip_address, user_agentRequest metadata, subject to the logging options.
user_type, user_idPolymorphic link to the authenticated user, if any.
payloadThe full raw cookie payload.
idempotency_keyUnique key per event, so a retried request does not create a second row.
created_atWhen the row was written. There is no updated_at.

The evidence fields (ip_address, user_agent, user_type/user_id, policy_hash) are always derived on the server. If you capture the IP behind a load balancer or CDN, configure Laravel's trusted proxies, or every row will contain the proxy's address.

Storing an IP address and user agent next to a consent decision is itself processing of personal data. Describe it in your privacy policy and set capture_ip and retention_days to match your data-minimisation obligations.

Exporting evidence

cookieconsent:export writes rows to standard output as JSON lines or CSV:

php artisan cookieconsent:export --format=csv > consent-evidence.csv
php artisan cookieconsent:export --format=json --user=42
php artisan cookieconsent:export --format=json --user=42 --user-type="App\\Models\\Admin"
php artisan cookieconsent:export --consent-id=abc123 --from=2026-01-01 --to=2026-06-30

A date-only --to includes the whole day. --user alone matches user_id only, so add --user-type when several models can own rows. --format accepts only json and csv.

Querying the model

Core45\CookieConsent\Models\ConsentLog has matching scopes:

ConsentLog::forConsentId('abc123')->get();
ConsentLog::forUser($user)->get();
ConsentLog::between('2026-01-01', '2026-06-30 23:59:59')->get();
ConsentLog::latestPerConsentId()->get(); // one row per consent_id, the most recent

Unlike the export command, between() uses its bounds as given: a date-only end bound means midnight at the start of that day. Pass an explicit time or a Carbon endOfDay() value to include the whole day.

Retention

cookieconsent:prune deletes rows older than logging.retention_days. With the default null it deletes nothing and says so. Schedule it if you want pruning to happen automatically:

// routes/console.php
Schedule::command('cookieconsent:prune')->daily();

Hardening at the database level

The append-only guard only covers saving an existing model instance. Mass updates, DB::table() queries and deletes bypass it. For a stronger guarantee, give the application's database user only SELECT and INSERT on the table:

-- MySQL
REVOKE UPDATE, DELETE ON consent_logs FROM 'app_user'@'%';

-- PostgreSQL
REVOKE UPDATE, DELETE ON consent_logs FROM app_user;

If you do this, run cookieconsent:prune through a separate, more privileged connection, because it needs DELETE.

Translations

The package ships bg, cs, de, el, en, es, et, fi, fr, hr, hu, it, lt, lv, nl, pl, pt, sk, sl, sq, sv and uk. Each locale has two files: cookieconsent.php, which maps onto the upstream language.translations.{locale} shape (consentModal, preferencesModal), and iframemanager.php, with per-service strings. Publish them to edit:

php artisan vendor:publish --tag=cookieconsent-lang

The banner uses app()->getLocale(). With translations_mode set to 'all', every available locale is embedded, so a client-side CookieConsent.setLanguage() works without a reload.

By default a published file is merged over the package file with array_replace_recursive. That means a shorter preferencesModal.sections list cannot remove the package's trailing sections, and a key you leave out falls back to the package text. To remove or rename something in this mode, override the key with a value. If you want your published file to be the whole truth for a locale, set translations_override to 'replace'; locales without a published file still use the package strings.

To add a language the package does not ship, create lang/vendor/cookieconsent/{locale}/cookieconsent.php (and iframemanager.php if you use embeds), using the English file as the template. A locale with no file at all falls back to the strings of app.fallback_locale.

JavaScript hooks

The library dispatches cc:onFirstConsent, cc:onConsent, cc:onChange, cc:onModalReady, cc:onModalShow and cc:onModalHide on window:

<script>
window.addEventListener('cc:onConsent', () => {
    if (window.CookieConsent.acceptedCategory('analytics')) {
        // ...
    }
});
</script>

To change the configuration in JavaScript before CookieConsent.run(config) is called, push to the cookieconsent:config stack. The config variable is already declared at that point:

@push('cookieconsent:config')
<script>
    config.cookie.expiresAfterDays = () => 365;
</script>
@endpush

The two combine into a Google Consent Mode v2 setup:

@push('cookieconsent:config')
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' });
    window.addEventListener('cc:onConsent', () => {
        if (window.CookieConsent.acceptedCategory('analytics')) {
            gtag('consent', 'update', { analytics_storage: 'granted' });
        }
    });
</script>
@endpush

A similar cookieconsent:iframemanager-config stack is rendered by @iframemanager after the imConfig variable is declared and before iframemanager starts.

Content Security Policy

Under a strict CSP, set csp_nonce to a callable that returns the nonce for the current request:

'csp_nonce' => fn () => \Illuminate\Support\Facades\Vite::cspNonce(),

Every script tag rendered by @cookieconsent and @iframemanager then carries the nonce. Scripts you push to the stacks yourself do not: add nonce="..." to them by hand.

Non-blocking assets

By default @cookieconsent renders a normal stylesheet link and script tag, which block the first render. Set 'defer_assets' => true to load the library with defer and the stylesheet without blocking. The banner still starts at DOMContentLoaded and stays hidden until its stylesheet has loaded. A small inline stub defines window.CookieConsent until the library arrives: read methods such as acceptedCategory() and validConsent() return what the library returns before run(), and other calls are queued and replayed. A queued call cannot return the library's answer, and properties added to the stub are lost when the library replaces it. The flag does not affect @iframemanager assets.

Filament

If filament/filament v3, v4 or v5 is installed, register the read-only consent log resource in your panel provider. Nothing needs publishing.

use Core45\CookieConsent\Filament\CookieConsentFilamentPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...your existing configuration
        ->plugin(CookieConsentFilamentPlugin::make());
}

A Consent Logs item then appears at /{your-panel-path}/consent-logs. The plugin detects the Filament major version and registers the matching resource; if you need the class name yourself, call Core45\CookieConsent\Filament\FilamentVersion::resourceClass(). There are no create or edit pages. Each row opens a read-only modal with every stored field. If you use strictAuthorization() with a ConsentLog policy, the policy needs both viewAny() and view().

Livewire, Turbo and dynamic markup

The library binds data-cc="show-preferencesModal" triggers once, when CookieConsent.run() executes. A trigger inserted later by a Livewire re-render, a Turbo or htmx swap, or your own JavaScript is not wired up. Call window.CookieConsent.showPreferences() from your own handler in that case.

Artisan commands

CommandWhat it does
php artisan cookieconsent:exportExports consent logs as JSON lines or CSV, with --user, --user-type, --consent-id, --from, --to and --format options.
php artisan cookieconsent:pruneDeletes rows older than logging.retention_days; does nothing when it is null.
php artisan cookieconsent:filamentReports the detected Filament version, the infolist API and the resource class the plugin will register.

Troubleshooting

  • Server-side checks always say "no consent". Check that cookie.useLocalStorage is off and look for the warning in your log. Also check that the visitor has answered the banner; before that, there is no cookie.
  • The banner looks old or behaves differently after an update. Re-publish the assets with --force. If you published the views, compare them with the package's copies.
  • Log requests fail with 419. The page was rendered without a valid CSRF token, for example from a full-page cache. Either keep logging.csrf on and avoid caching the token, or set it to false, which removes CSRF validation from the log route.
  • Log requests fail with 422. The payload names a category that is not in categories, usually after a category was removed while visitors still hold old cookies.
  • Every row has the same IP address. Configure trusted proxies.
  • A "Manage cookies" link does nothing. It was inserted after run(); call window.CookieConsent.showPreferences() instead.
  • An embed never loads. Check that iframemanager.enabled is true, that @iframemanager is in the layout, and that the service's category exists in categories.
  • The consent log item is missing in Filament. The plugin must be added to the panel, because panel discovery does not scan packages. Then check your ConsentLog policy.
  • A section you deleted from a published lang file still shows. That is the merge behaviour described under "Translations"; use 'replace' or override the key.
  • Scripts are blocked under CSP. Set csp_nonce, and add the nonce to scripts you push yourself.

Upgrading

The package follows Semantic Versioning, and the CHANGELOG in the repository lists what to do for each release. The points that need action:

  • After any release that updates the bundled library, re-publish the assets with --force. Release 3.5.0 moved to cookieconsent 3.3.0; with stale assets the site keeps serving the old files. If you published the views, re-publish deferred-assets.blade.php too.
  • Since 3.5.0, in opt-out mode, acceptedCategory() and acceptedService() return true for default-enabled categories before the visitor chooses. Code that read false as "no choice yet" should use validConsent().
  • Since 3.5.1, the log endpoint accepts only JSON. The bundled script already sends JSON; custom clients must too.
  • 3.0.0 dropped Laravel 11 and 2.0.0 requires PHP 8.4. Stay on ^2.0 or ^1.1 respectively if you cannot upgrade.

Licence and contributing

The package is open source under the MIT licence. Issues, questions and pull requests are welcome in the core45/laravel-cookieconsent repository on GitHub. If you also need a captcha on your forms, our Laravel hCaptcha package follows the same approach. We build web applications in Laravel, and if you would like us to integrate consent handling into yours, get in touch.

More work

Klimek Academy

Klimek Academy

Klimek Academy

An online shop and learning platform for the Holistic Fascia Release academy. It sells in-person courses, subscription courses and digital products in two languages and three currencies, and releases course chapters in step with each payment.

Read the case study
Clic A Tour

Clic A Tour

Clic A Tour

A multilingual marketplace for tours and activities worldwide, with a booking and payment flow in 13 languages and 19 currencies, and a back office that keeps supplier inventory in sync automatically.

Read the case study

Got a project that needs to move?

Tell us what you want to build or improve. We will reply with specifics: what we suggest, in what order, and what we will need from you.