PHPackages                             consent-studio/laravel - 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. [API Development](/categories/api)
4. /
5. consent-studio/laravel

ActiveLibrary[API Development](/categories/api)

consent-studio/laravel
======================

Laravel package for Consent Studio CMP (Consent Management Platform) integration

1.0.0(6mo ago)00[1 issues](https://github.com/vallonic/consent-studio-laravel/issues)MITPHPPHP ^8.1

Since Nov 12Pushed 6mo agoCompare

[ Source](https://github.com/vallonic/consent-studio-laravel)[ Packagist](https://packagist.org/packages/consent-studio/laravel)[ RSS](/packages/consent-studio-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

Consent Studio Laravel Package
==============================

[](#consent-studio-laravel-package)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e037e85fe5ce2c4a4b9a5cf85804cd4bee594d57e20b3b0f918d8d0dcadf694e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f6e73656e742d73747564696f2f6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/consent-studio/laravel)

Laravel package for [Consent Studio](https://consent.studio) CMP (Consent Management Platform) integration. Easily integrate GDPR-compliant cookie consent management into your Laravel applications.

Features
--------

[](#features)

- 🇪🇺 **European CMP** - Built in the Netherlands with 100% European-owned infrastructure
- 🚀 **Simple Integration** - Add consent management with just a few lines of code
- ⚙️ **Google Consent Mode v2** - Full support for Google's consent framework
- 🎨 **Smart Blade Directives** - Automatically block content based on consent categories
- 🔧 **Highly Configurable** - Customize all settings via Laravel config

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

[](#installation)

Install the package via Composer:

```
composer require consent-studio/laravel
```

Publish the configuration file:

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

This will create a `config/consent-studio.php` file where you can customize your settings.

Basic Usage
-----------

[](#basic-usage)

### 1. Add the Consent Studio Script

[](#1-add-the-consent-studio-script)

Add the `@consentstudio` directive to your layout file, typically in the `` section before any other tracking scripts:

```

    My Laravel App

    @consentstudio

    @yield('content')

```

### 2. Wrap Content That Requires Consent

[](#2-wrap-content-that-requires-consent)

Use the `@consent` directive to automatically block content until proper consent is given:

```
{{-- Marketing scripts --}}
@consent('marketing')

    fbq('track', 'PageView');

@endconsent

{{-- Analytics scripts --}}
@consent('analytics')

@endconsent

{{-- YouTube embeds --}}
@consent('marketing')

@endconsent
```

Consent Categories
------------------

[](#consent-categories)

The `@consent` directive supports the following categories:

- `functional` - Essential functionality (usually not blocked)
- `analytics` - Analytics and statistics tracking
- `marketing` - Marketing, advertising, and social media
- `neutral` - Neutral category (not assigned to any specific consent type)

**Note:** The directive accepts only a single category string, not an array.

Reading Consent State in Controllers
------------------------------------

[](#reading-consent-state-in-controllers)

You can read the user's consent state in your controllers, middleware, or anywhere in your Laravel application using the `ConsentStudio` facade or the `consent()` helper function.

### Facade Usage

[](#facade-usage)

```
use ConsentStudio\Laravel\Facades\ConsentStudio;

// Check if user has seen the banner
if (ConsentStudio::seenBanner()) {
    // Banner was shown to the user
}

// Get the consent ID
$consentId = ConsentStudio::id(); // Returns string|null

// Check if a specific consent category is granted
if (ConsentStudio::granted('marketing')) {
    // Marketing consent is granted
}

// Alternative method (alias)
if (ConsentStudio::has('analytics')) {
    // Analytics consent is granted
}

// Check if any of multiple categories are granted
if (ConsentStudio::any(['marketing', 'analytics'])) {
    // At least one is granted
}

// Check if all of multiple categories are granted
if (ConsentStudio::all(['functional', 'analytics'])) {
    // Both are granted
}

// Get all granted consent categories
$consents = ConsentStudio::all(); // Returns array: ['functional', 'analytics', 'marketing']

// Get complete consent state
$state = ConsentStudio::state();
// Returns: ['id' => 'xxx', 'seen' => true, 'consents' => ['functional', 'analytics']]
```

### Helper Function Usage

[](#helper-function-usage)

```
// No arguments: returns the manager instance for chaining
consent()->id(); // 'abc-123-def'
consent()->seenBanner(); // true

// String argument: checks if the category is granted
consent('marketing'); // true or false

// Array argument: checks if any of the categories are granted
consent(['marketing', 'analytics']); // true or false
```

### Practical Examples

[](#practical-examples)

**Conditional Logic in Controllers:**

```
public function index()
{
    // Show different content based on consent
    if (ConsentStudio::granted('marketing')) {
        // Load personalized recommendations
        $recommendations = $this->getPersonalizedRecommendations();
    } else {
        // Load generic content
        $recommendations = $this->getGenericRecommendations();
    }

    return view('home', compact('recommendations'));
}
```

**Middleware Example:**

```
public function handle($request, Closure $next)
{
    if (!consent('analytics')) {
        // Skip analytics tracking
        config(['analytics.enabled' => false]);
    }

    return $next($request);
}
```

**Conditional View Rendering:**

```
// In your controller
return view('dashboard', [
    'canShowAds' => ConsentStudio::granted('marketing'),
    'consentId' => ConsentStudio::id(),
]);
```

```
{{-- In your Blade view --}}
@if(consent('marketing'))

@endif
```

### Cookie Details

[](#cookie-details)

The consent state is stored in the following cookies:

- `consent-studio__seen` - Whether the user has seen the banner (true/false)
- `consent-studio__consent-id` - The unique consent ID for this user
- `consent-studio__storage` - URL-encoded JSON array of granted consents (e.g., `["functional","analytics","marketing"]`)

All methods automatically handle cookie decoding and edge cases (missing cookies, malformed data, etc.).

### CLI and Queue Jobs

[](#cli-and-queue-jobs)

When used in CLI contexts (artisan commands, queue jobs, etc.) where no HTTP request is available, all methods return safe defaults:

- `seenBanner()` returns `false`
- `id()` returns `null`
- `granted()`, `has()`, `any()`, `all()` return `false` or `[]`
- No errors or exceptions are thrown

This ensures your code works reliably in all Laravel contexts without requiring conditional checks.

Blade Directive Examples
------------------------

[](#blade-directive-examples)

### Inline Scripts

[](#inline-scripts)

```
@consent('marketing')

    console.log('This will be blocked until marketing consent is granted');
    gtag('event', 'page_view');

@endconsent
```

**Output:**

```

    console.log('This will be blocked until marketing consent is granted');
    gtag('event', 'page_view');

```

### External Scripts

[](#external-scripts)

```
@consent('analytics')

@endconsent
```

**Output:**

```

```

### Iframes (YouTube, Vimeo, etc.)

[](#iframes-youtube-vimeo-etc)

```
@consent('marketing')

@endconsent
```

**Output:**

```

```

### Images

[](#images)

```
@consent('marketing')

@endconsent
```

**Output:**

```

```

### Video Elements

[](#video-elements)

```
@consent('marketing')

@endconsent
```

**Output:**

```

```

Manual HTML Usage
-----------------

[](#manual-html-usage)

If you prefer not to use the Blade directives, you can manually add the consent blocking attributes:

### External Scripts

[](#external-scripts-1)

```

```

### Inline Scripts

[](#inline-scripts-1)

```

    fbq('track', 'PageView');

```

### Iframes

[](#iframes)

```

```

### Images

[](#images-1)

```

```

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

[](#configuration)

The `config/consent-studio.php` file provides full control over Consent Studio's behavior:

### Google Consent Mode

[](#google-consent-mode)

```
'google_consent_mode' => [
    'enabled' => true,
    'wait_for_update' => 500,  // Milliseconds to wait for consent update
    'ads_data_redaction' => true,
    'url_passthrough' => false,

    'defaults' => [
        [
            'ad_storage' => 'denied',
            'ad_user_data' => 'denied',
            'ad_personalization' => 'denied',
            'analytics_storage' => 'denied',
            'functionality_storage' => 'granted',
            'personalization_storage' => 'granted',
            'security_storage' => 'granted',
        ],
    ],
],
```

### Region-Specific Consent Defaults

[](#region-specific-consent-defaults)

You can configure different default consent states for different regions:

```
'defaults' => [
    [
        'ad_storage' => 'denied',
        'analytics_storage' => 'denied',
        'region' => ['US', 'CA'],  // North America
    ],
    [
        'ad_storage' => 'granted',
        'analytics_storage' => 'granted',
        'region' => ['GB'],  // United Kingdom
    ],
],
```

### Environment Variables

[](#environment-variables)

You can also configure settings via environment variables in your `.env` file:

```
CONSENT_STUDIO_GCM_ENABLED=true
CONSENT_STUDIO_GCM_WAIT=500
CONSENT_STUDIO_GCM_ADS_REDACTION=true
CONSENT_STUDIO_GCM_URL_PASSTHROUGH=false
CONSENT_STUDIO_DEBUG=false
```

### Debug Mode

[](#debug-mode)

Enable debug mode during development:

```
'debug' => env('CONSENT_STUDIO_DEBUG', false),
```

Or in `.env`:

```
CONSENT_STUDIO_DEBUG=true
```

Styling Blocked Content
-----------------------

[](#styling-blocked-content)

Consent Studio automatically adds the `.insufficient-consent` CSS class to blocked elements. You can style these elements to provide visual feedback:

```
[cs-require].insufficient-consent {
    filter: blur(10px);
    opacity: 0.5;
    pointer-events: none;
}

iframe[cs-require].insufficient-consent {
    background: #f0f0f0;
    position: relative;
}

iframe[cs-require].insufficient-consent::after {
    content: 'Please accept cookies to view this content';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
    color: #666;
}
```

Google Tag Manager Integration
------------------------------

[](#google-tag-manager-integration)

If you're using Google Tag Manager, make sure to load it **after** the Consent Studio script:

```
@consentstudio

(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXXX');

```

How It Works
------------

[](#how-it-works)

### The `@consent` Directive

[](#the-consent-directive)

The `@consent` directive intelligently detects the type of HTML element and applies the appropriate transformation:

1. **External resources** (iframe, script, img, video, audio, embed, source, track):

    - Moves `src` attribute to `data-src`
    - Sets `src=""` (empty)
    - Adds `cs-require="category"` attribute
2. **Inline scripts**:

    - Changes `type` to `type="text/plain"`
    - Adds `cs-require="category"` attribute
3. **Consent Studio activation**:

    - When user grants consent, Consent Studio automatically restores the original `src` values
    - Elements are activated and loaded
    - The `.insufficient-consent` class is removed

Testing
-------

[](#testing)

Run the tests with:

```
composer test
```

Documentation
-------------

[](#documentation)

For more information about Consent Studio CMP:

- [Official Documentation](https://learn.consent.studio)
- [Support](mailto:support@consent.studio)

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.0 or 11.0

License
-------

[](#license)

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

Support
-------

[](#support)

If you discover any security vulnerabilities or bugs, please email .

Credits
-------

[](#credits)

- Built by [Consent Studio](https://consent.studio)
- 🇳🇱 Made in the Netherlands
- 🇪🇺 100% European-owned infrastructure

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance68

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

187d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/17dee3b4fc5169d187d442a6054d82c16a78a0e152d11c3d3332e23428adfcc8?d=identicon)[thierrymaasdam](/maintainers/thierrymaasdam)

---

Top Contributors

[![thierrymaasdam](https://avatars.githubusercontent.com/u/19410581?v=4)](https://github.com/thierrymaasdam "thierrymaasdam (5 commits)")

---

Tags

laravelcookiegdprconsent-managementconsentcmp

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[mollie/laravel-mollie

Mollie API client wrapper for Laravel &amp; Mollie Connect provider for Laravel Socialite

3624.1M28](/packages/mollie-laravel-mollie)[api-ecosystem-for-laravel/dingo-api

A RESTful API package for the Laravel and Lumen frameworks.

3121.5M10](/packages/api-ecosystem-for-laravel-dingo-api)[statikbe/laravel-cookie-consent

Cookie consent modal for EU

213396.7k](/packages/statikbe-laravel-cookie-consent)[mll-lab/laravel-graphiql

Easily integrate GraphiQL into your Laravel project

683.2M9](/packages/mll-lab-laravel-graphiql)[devrabiul/laravel-cookie-consent

A GDPR-compliant cookie consent solution for Laravel applications with fully customizable cookie banners, granular consent control, and enterprise-grade compliance features.

17633.8k1](/packages/devrabiul-laravel-cookie-consent)

PHPackages © 2026

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