### Install Laravel Cookie Consent
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Use Composer to install the package. The service provider is automatically registered.
```bash
composer require whitecube/laravel-cookie-consent
```
--------------------------------
### Install Laravel Cookie Consent
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Install the package using Composer and publish its scaffolding files with Artisan commands. This includes service provider stubs, configuration files, views, and translation files.
```bash
composer require whitecube/laravel-cookie-consent
# Publish the app-level CookiesServiceProvider stub
php artisan vendor:publish --tag=laravel-cookie-consent-service-provider
# Publish the config file (config/cookieconsent.php)
php artisan vendor:publish --tag=laravel-cookie-consent-config
# Optional: publish customizable Blade views
php artisan vendor:publish --tag=laravel-cookie-consent-views
# Optional: publish translation files
php artisan vendor:publish --tag=laravel-cookie-consent-lang
```
--------------------------------
### Configure Cookie Domain for Subdomains
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
To store user preferences across multiple sub-domains, configure the `cookieconsent.cookie.domain` setting in `config/cookieconsent.php`. Ensure the domain starts with a leading dot.
```php
'cookie' => [
// ...
'domain' => '.mydomain.com', // notice the leading "."
]
```
--------------------------------
### Custom Cookie Attributes
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
You can set and get custom attributes on cookie instances using magic properties or `setAttribute`/`getAttribute` methods. These can also be called as chainable methods.
```APIDOC
## Custom cookie attributes
### Description
When building your own cookie notice designs, you might need extra attributes on the `Cookie` instances. We've got you covered!
### Example
```php
$cookie->color = 'warning';
echo $cookie->color; // "warning"
```
Behind the scenes, these magic attributes use the `setAttribute` and `getAttribute` methods:
```php
$cookie->setAttribute('icon', 'brightness');
echo $cookie->getAttribute('icon'); // "brightness"
```
But since all other cookie definition methods are chainable, you can also call custom attributes as chainable methods:
```php
$cookie->subtitle('Darkmode preferences')->checkmark(true);
echo $cookie->subtitle; // "brightness"
echo $cookie->checkmark ? 'on' : 'off'; // "on"
```
```
--------------------------------
### Implement Consent Callback
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Use the `accepted()` method on an optional cookie to define actions when consent is given. This callback can set HTTP cookies or inject script tags into the response.
```php
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
use App\Services\ThemeService;
Cookies::optional()
->name('theme')
->description('Stores your chosen color theme.')
->duration(525600) // 1 year
->accepted(function(Consent $consent, ThemeService $theme) {
$consent
// Set a cookie on the HTTP response
->cookie(
value: $theme->getDefault(), // Cookie value
path: '/',
domain: null,
secure: true,
httpOnly: false, // Accessible via document.cookie
sameSite: 'Lax',
)
// Inject a script tag into
when consent exists
->script('');
});
```
--------------------------------
### Check Consent with Cookies Facade
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Use the `Cookies` facade to check if a specific cookie has received user consent. This is a convenient way to conditionally execute code based on consent status.
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
if(Cookies::hasConsentFor('my_cookie_name')) {
// ...
}
```
--------------------------------
### Cookies::essentials()
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Returns or creates the 'essentials' category for cookies that are always consented and cannot be opted out. The package's own consent-tracking cookie is automatically added here.
```APIDOC
## `Cookies::essentials()` — Essential Cookies Category
Returns (or creates) the built-in `essentials` category. Cookies registered here are automatically consented — they can never be opted out. The package's own consent-tracking cookie is always added to this category automatically.
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
// Register Laravel's session and CSRF cookies
Cookies::essentials()
->session() // name = config('session.cookie'), duration = config('session.lifetime')
->csrf(); // name = 'XSRF-TOKEN', duration = config('session.lifetime')
// Or define custom essential cookies
Cookies::essentials()
->name('remember_me')
->description('Keeps you logged in between visits.')
->duration(60 * 24 * 30); // 30 days
```
```
--------------------------------
### Configure Sub-domain Consent Sharing
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Set the 'domain' configuration option in `config/cookieconsent.php` with a leading dot to enable consent sharing across all sub-domains. This ensures a single consent prompt covers the entire domain.
```php
// config/cookieconsent.php
'cookie' => [
'name' => env('APP_NAME') . '_cookie_consent',
'duration' => 60 * 24 * 365,
'domain' => '.mydomain.com', // Leading dot = shared across *.mydomain.com
],
```
--------------------------------
### Register Optional Cookies
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Define optional cookies that require explicit user opt-in. The `accepted()` callback handles setting the cookie and injecting scripts when consent is granted.
```php
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
Cookies::optional()
->name('ab_variant')
->description('Stores which A/B test variant was shown to this user.')
->duration(60 * 24 * 7) // 1 week
->accepted(function(Consent $consent) {
$variant = ['A', 'B'][rand(0, 1)];
$consent->cookie(value: $variant, httpOnly: false); // Readable by JS
});
```
--------------------------------
### Define a Cookie with Fluent Methods
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Define a cookie within a targeted category using fluent methods for name, description, and duration.
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
Cookies::essentials()
->name('darkmode_enabled')
->description('Lorem ipsum')
->duration(120);
```
--------------------------------
### Register All Application Cookies
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Use this method to declare all cookies the application uses. It's called once per request before the consent state is evaluated.
```php
namespace App\Providers;
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Cookie;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
use Whitecube\LaravelCookieConsent\CookiesServiceProvider as ServiceProvider;
use App\Services\DarkmodeService;
class CookiesServiceProvider extends ServiceProvider
{
protected function registerCookies(): void
{
// ── Essentials (always consented, cannot be opted out) ──────────────
Cookies::essentials()
->session() // Registers config('session.cookie')
->csrf(); // Registers XSRF-TOKEN
// ── Analytics (Google Analytics shorthand) ───────────────────────────
// Automatically registers _ga, _ga_ID, _gid, _gat cookies AND
// injects the gtag.js ');
});
// ── Chaining multiple cookies in one category ────────────────────────
Cookies::optional()
->cookie(fn(Cookie $c) => $c->name('ui_lang')->duration(525600)->description('Stores UI language preference.'))
->cookie(fn(Cookie $c) => $c->name('font_size')->duration(525600)->description('Stores chosen font size.'));
}
}
```
--------------------------------
### API Routes - POST Endpoints
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
The package registers five POST routes that return JSON. These are typically consumed by the built-in JavaScript library or custom AJAX code.
```APIDOC
## API Routes — POST Endpoints
The package registers five routes under the configured prefix. All POST routes return JSON and are consumed by the built-in JS library or custom AJAX code.
```js
// Using the built-in LaravelCookieConsent JS object (auto-initialised via @cookieconsentscripts)
// Accept every cookie category
LaravelCookieConsent.acceptAll()
.then(() => document.getElementById('cookies-policy')?.remove());
// Accept essentials only
LaravelCookieConsent.acceptEssentials();
// Accept specific categories (checkbox form values)
const data = new FormData(document.querySelector('.cookies__customize'));
LaravelCookieConsent.configure(data);
// Reset consent — re-displays the modal
LaravelCookieConsent.reset();
```
Direct HTTP examples (e.g. from a custom front-end):
```bash
# Accept all cookies
curl -X POST https://example.com/cookie-consent/accept-all \
-H "X-CSRF-TOKEN: " \
-H "Accept: application/json"
# Response: {"scripts": [""], "notice": null}
# Accept selected categories
curl -X POST https://example.com/cookie-consent/configure \
-H "X-CSRF-TOKEN: " \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "categories[]=essentials&categories[]=analytics"
# Reset consent
curl -X POST https://example.com/cookie-consent/reset \
-H "X-CSRF-TOKEN: "
# Response: {"notice": ""}
```
```
--------------------------------
### Configure Category Translations
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Add human-readable titles and descriptions for categories by updating the `cookieConsent.cookies.categories.[category-key]` translations in your configuration.
```php
return [
// ...
'categories' => [
// ...
'my-custom-category' => [
'title' => 'My custom category of cookies',
'description' => 'A short description of what these cookies are meant for.',
],
// ...
],
// ...
];
```
--------------------------------
### Checking for Consent using Dependency Injection
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Inject the `CookiesManager` into your controllers or other classes to check for user consent.
```APIDOC
### Using dependency injection
### Description
Useful when working with methods resolved by Laravel's Service Container. Inject `CookiesManager` to check for consent.
### Example
```php
use Whitecube\LaravelCookieConsent\CookiesManager;
class FooController
{
public function __invoke(CookiesManager $cookies)
{
if($cookies->hasConsentFor('my_cookie_name')) {
// ...
}
}
}
```
```
--------------------------------
### Cookies::analytics()->google()
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Integrates Google Analytics by registering standard GA cookies and injecting gtag.js scripts when consent is granted. Automatically handles `_ga`, `_ga_ID`, `_gid`, and `_gat` cookies.
```APIDOC
## `Cookies::analytics()->google()` — Google Analytics Integration
Registers all four standard Google Analytics cookies (`_ga`, `_ga_ID`, `_gid`, `_gat`) as a named group and, when consent is granted, automatically injects the `gtag.js` loader and configuration scripts into ``.
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
// In CookiesServiceProvider::registerCookies()
Cookies::analytics()->google(
id: 'G-XXXXXXXXXX', // Your GA4 measurement ID
anonymizeIp: true, // Adds anonymize_ip:true to gtag config (default: true)
);
// Once consent is granted the package automatically injects:
//
//
```
```
--------------------------------
### Customization: Views
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Customize the appearance of the cookie notice by publishing and modifying the package's views.
```APIDOC
## Customization
### The views
### Description
A good starting point is to take a look at this package's default markup. If not already published, you can access the views using `php artisan vendor:publish --tag=laravel-cookie-consent-views`, this will copy our blade files to your app's `resources/views/vendor/cookie-consent` directory.
In order to add buttons, we'd recommend using the package's `@cookieconsentbutton()` blade directive:
- `@cookieconsentbutton('accept.all')`: renders a button targetting this package's "consent to all cookies" API route ;
- `@cookieconsentbutton('accept.essentials')`: renders a button targetting this package's "consent to essential cookies only" API route ;
- `@cookieconsentbutton('accept.configuration')`: renders a button targetting this package's "consent to custom cookies selection" API route. Beware that this route requires the selected cookie categories as the request's payload ;
- `@cookieconsentbutton('reset')`: renders a button targetting this package's "reset cookie configuration" API route.
```
--------------------------------
### Define Accepted Cookie Callback
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Use the `accepted` method to define a callback that executes when consent is granted for a cookie category. This callback can configure cookies and script tags to be added to the response.
```php
use Whitecube\LaravelCookieConsent\Consent;
$cookie->accepted(function(Consent $consent) {
$consent->cookie(value: 'off')->script('');
});
```
```php
use App\Services\MyDependencyService;
use Whitecube\LaravelCookieConsent\Consent;
$cookie->accepted(function(Consent $consent, MyDependencyService $service) {
$consent->script($service->getScriptTag());
});
```
--------------------------------
### Check Cookie Consent (Dependency Injection)
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Inject the `CookiesManager` class directly into your controllers or services for testable consent checks. This allows for easier unit testing of consent-related logic.
```php
use Whitecube\LaravelCookieConsent\CookiesManager;
class PersonalizationController
{
public function show(CookiesManager $cookies)
{
$data = [
'darkmode' => $cookies->hasConsentFor('darkmode_enabled'),
'analytics' => $cookies->hasConsentFor('ga'),
'variant' => $cookies->hasConsentFor('ab_variant')
? request()->cookie('ab_variant')
: null,
];
return view('dashboard', $data);
}
}
```
--------------------------------
### Define and Register Cookies
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Define essential, analytics, and optional cookies within the registerCookies method of your CookiesServiceProvider. This method is called during application bootstrapping.
```php
namespace App\Providers;
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
use Whitecube\LaravelCookieConsent\CookiesServiceProvider as ServiceProvider;
class CookiesServiceProvider extends ServiceProvider
{
/**
* Define the cookies users should be aware of.
*/
protected function registerCookies(): void
{
if (app()->environment() === 'production') {
// Register Laravel's base cookies under the "required" cookies section:
Cookies::essentials()
->session()
->csrf();
// Register all Analytics cookies at once using one single shorthand method:
Cookies::analytics(
id: config('cookieconsent.google_analytics.id')
anonymizeIp: config('cookieconsent.google_analytics.anonymize_ip')
);
// Register custom cookies under the pre-existing "optional" category:
Cookies::optional()
->name('darkmode_enabled')
->description('This cookie helps us remember your preferences regarding the interface\'s brightness.')
->duration(120)
->accepted(fn(Consent $consent, MyDarkmode $darkmode) => $consent->cookie(value: $darkmode->getDefaultValue()));
}
}
}
```
--------------------------------
### Chain Cookie Definitions
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Define multiple cookies within a category by chaining the `cookie` method. Each `cookie` method accepts a closure that receives a `Cookie` instance to configure.
```php
use Whitecube\LaravelCookieConsent\Cookie;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
Cookies::essentials()
->cookie(function(Cookie $cookie) {
$cookie->name('darkmode_enabled')
->description('Lorem ipsum')
->duration(120);
})
->cookie(function(Cookie $cookie) {
$cookie->name('high_contrast_enabled')
->description('Lorem ipsum')
->duration(60 * 24 * 365);
});
```
--------------------------------
### Cookies::optional()
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Returns or creates the 'optional' category for cookies that require explicit user opt-in. The `accepted()` callback is executed on requests where consent has been granted.
```APIDOC
## `Cookies::optional()` — Optional Cookies Category
Returns (or creates) the built-in `optional` category for feature cookies that require explicit user opt-in. The `accepted()` callback fires on every request where consent was previously granted.
```php
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
Cookies::optional()
->name('ab_variant')
->description('Stores which A/B test variant was shown to this user.')
->duration(60 * 24 * 7) // 1 week
->accepted(function(Consent $consent) {
$variant = ['A', 'B'][rand(0, 1)];
$consent->cookie(value: $variant, httpOnly: false); // Readable by JS
});
```
```
--------------------------------
### Accepted Callback
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
The `accepted` callback is invoked when consent is granted for a cookie category. It receives a `Consent` object to configure script tags and cookies.
```APIDOC
## `accepted(Closure $callback)`
### Description
The optional "accepted" callback gets invoked when consent is granted to the category a cookie is attached to. This happens once the user configures their cookie preferences but also each time an incoming request is handled afterwards.
The callback receives at least one parameter, `Consent $consent`, which is an object used to configure consent output:
- `script(string $tag)`: defines a script tag that will be added to the layout's `` only when consent has been granted ;
- `cookie(string $value, ?string $path = null, ?string $domain = null, ?bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = null)`: defines a cookie that will be added to the response when consent has been granted. Note that it doesn't need a name and a duration anymore since those settings have already been defined using the `name()` and `duration()` methods described above.
### Example
```php
use Whitecube\LaravelCookieConsent\Consent;
$cookie->accepted(function(Consent $consent) {
$consent->cookie(value: 'off')->script('');
});
```
Other parameters can be type-hinted and will be resolved by Laravel's Service Container:
```php
use App\Services\MyDependencyService;
use Whitecube\LaravelCookieConsent\Consent;
$cookie->accepted(function(Consent $consent, MyDependencyService $service) {
$consent->script($service->getScriptTag());
});
```
```
--------------------------------
### Cookie::accepted() - Consent Callback
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Defines the action to perform when a cookie's category is consented to. This method accepts a callback that receives a `Consent` object and can resolve additional parameters from the service container.
```APIDOC
## `Cookie::accepted()` — Consent Callback
Defines the action to perform when a cookie's category is consented to. Receives a `Consent` object as its first argument; additional parameters are resolved from Laravel's Service Container.
```php
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
use App\Services\ThemeService;
Cookies::optional()
->name('theme')
->description('Stores your chosen color theme.')
->duration(525600) // 1 year
->accepted(function(Consent $consent, ThemeService $theme) {
$consent
// Set a cookie on the HTTP response
->cookie(
value: $theme->getDefault(), // Cookie value
path: '/',
domain: null,
secure: true,
httpOnly: false, // Accessible via document.cookie
sameSite: 'Lax',
)
// Inject a script tag into when consent exists
->script('');
});
```
```
--------------------------------
### Check Cookie Consent (Facade)
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Use `Cookies::hasConsentFor()` to check if consent exists for a specific cookie or group. This is useful in controllers, middleware, or view composers to conditionally execute code or display content.
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
// In a controller, middleware, or view composer
if (Cookies::hasConsentFor('darkmode_enabled')) {
// Safe to read/write the darkmode cookie
$value = request()->cookie('darkmode_enabled');
}
// Check consent for a Google Analytics group (checks all _ga*, _gid, _gat cookies)
if (Cookies::hasConsentFor('ga')) {
// Analytics group was consented
}
// In Blade
@if(\"Whitecube\LaravelCookieConsent\Facades\Cookies::hasConsentFor('ab_variant'))
Your variant: {{ cookie('ab_variant') }}
@endif
```
--------------------------------
### Checking for Consent using Cookies Facade
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Check if a specific cookie has been consented to using the `Cookies` facade.
```APIDOC
## Checking for consent
### Using the `Cookies` facade
### Description
The `Cookies` facade is automatically discovered when installing this package. Use it to check for user consent on specific cookies.
### Example
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
if(Cookies::hasConsentFor('my_cookie_name')) {
// ...
}
```
```
--------------------------------
### Check if Consent Notice Should Display
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Use `CookiesManager::shouldDisplayNotice()` to determine if the consent modal needs to be shown. This is typically used in middleware to redirect users to a consent page if no consent is recorded or if new cookies require re-consent.
```php
use Whitecube\LaravelCookieConsent\CookiesManager;
// Useful in middleware to force redirect to a consent page
class EnsureCookieConsent
{
public function handle(Request $request, Closure $next)
{
$cookies = app(CookiesManager::class);
if ($cookies->shouldDisplayNotice() && ! $request->is('cookie-policy')) {
// Log that a new consent prompt is needed
logger()->info('Cookie consent required for ' . $request->ip());
}
return $next($request);
}
}
```
--------------------------------
### Manage Cookie Consent via HTTP POST Requests
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Interact with the cookie consent API endpoints using direct HTTP POST requests, suitable for custom front-ends or testing. Ensure to include the CSRF token and appropriate headers. Responses are in JSON format.
```bash
# Accept all cookies
curl -X POST https://example.com/cookie-consent/accept-all \
-H "X-CSRF-TOKEN: " \
-H "Accept: application/json"
# Response: {"scripts": [""], "notice": null}
# Accept selected categories
curl -X POST https://example.com/cookie-consent/configure \
-H "X-CSRF-TOKEN: " \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "categories[]=essentials&categories[]=analytics"
# Reset consent
curl -X POST https://example.com/cookie-consent/reset \
-H "X-CSRF-TOKEN: "
# Response: {"notice": ""}
```
--------------------------------
### Register CookiesServiceProvider
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Register the published service provider in your Laravel application's configuration. The location depends on your Laravel version.
```php
// bootstrap/providers.php (Laravel 11+)
return [
App\Providers\AppServiceProvider::class,
App\Providers\CookiesServiceProvider::class, // Must come after RouteServiceProvider on L9/10
];
```
--------------------------------
### Render Cookie Consent UI with Blade Directives
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Integrate the consent UI into your Blade layouts using directives. Ensure the CookiesServiceProvider is registered. @cookieconsentscripts loads package JS and consented scripts, @cookieconsentview renders the alert/modal, and @cookieconsentbutton provides a standalone reset button.
```blade
{{-- resources/views/layouts/app.blade.php --}}
@yield('title')
{{-- Loads the package JS (deferred) + any consented
//
```
--------------------------------
### Generate Cookie Policy Table
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Use the Cookies facade to dynamically generate tables detailing cookie categories, names, descriptions, and durations for your Cookie Policy page. This ensures your policy stays up-to-date with the package's configuration.
```blade
Cookie Policy
...
How do we use cookies?
@foreach(Cookies::getCategories() as $category)
{{ $category->title }}
| Cookie |
Description |
Duration |
@foreach($category->getCookies() as $cookie)
| {{ $cookie->name }} |
{{ $cookie->description }} |
{{
Carbon
::now()
->diffForHumans(
Carbon
::now()
->addMinutes($cookie->duration),
true
)
}} |
@endforeach
@endforeach
...
```
--------------------------------
### Register Cookies Service Provider (Laravel 11+)
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Register the CookiesServiceProvider in your bootstrap/providers.php file for Laravel versions 11 and above.
```php
return [
App\Providers\AppServiceProvider::class,
App\Providers\CookiesServiceProvider::class,
];
```
--------------------------------
### Display Cookie Policy Information with Blade
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Generate a dynamic cookie policy page by iterating through registered categories and their cookies using the Cookies::getCategories() method. This allows for a self-updating policy page.
```blade
{{-- resources/views/cookie-policy.blade.php --}}
Cookie Policy
We use cookies to improve your experience. Below is a full list of the cookies we may set.
@foreach(\Whitecube\LaravelCookieConsent\Facades\Cookies::getCategories() as $category)
{{ $category->title }}
@if($category->description)
{{ $category->description }}
@endif
| Cookie name |
Purpose |
Expires |
@foreach($category->getCookies() as $cookie)
{{ $cookie->name }} |
{{ $cookie->description }} |
{{ \Carbon\Carbon::now()->diffForHumans(\Carbon\Carbon::now()->addMinutes($cookie->duration), true) }} |
@endforeach
@endforeach
```
--------------------------------
### Set Custom Cookie Attributes in PHP
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Use magic setters, getters, or chainable methods to define custom attributes for a Cookie instance. Access attributes via properties or explicit methods. Ensure the cookie is marked as optional if it's not essential.
```php
use Whitecube\LaravelCookieConsent\Cookie;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
Cookies::optional()
->cookie(function(Cookie $cookie) {
$cookie
->name('ui_prefs')
->duration(525600)
->description('Stores UI preferences.')
// Custom attributes — chainable method syntax
->icon('settings')
->badgeColor('blue')
->required(false);
// Access via property
echo $cookie->icon; // "settings"
echo $cookie->badgeColor; // "blue"
// Or via explicit methods
$cookie->setAttribute('vendor', 'First-party');
echo $cookie->getAttribute('vendor'); // "First-party"
});
```
--------------------------------
### Define a Custom Cookie Category
Source: https://github.com/whitecube/laravel-cookie-consent/blob/main/README.md
Use the `category` method on the Cookies facade to define a new custom cookie category. The optional second parameter can be used to provide a custom category class.
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
$category = Cookies::category(key: 'my-custom-category');
```
```php
use Whitecube\LaravelCookieConsent\Facades\Cookies;
$category = Cookies::category(key: 'my-custom-category', maker: function(string $key) {
return new MyCustomCategory($key);
});
```
--------------------------------
### Manage Cookie Consent via JavaScript API
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Use the auto-initialized LaravelCookieConsent JS object to manage user consent. Call methods like acceptAll(), acceptEssentials(), configure(), and reset() to interact with the consent system. These methods are typically consumed by custom AJAX code or the built-in JS library.
```javascript
// Using the built-in LaravelCookieConsent JS object (auto-initialised via @cookieconsentscripts)
// Accept every cookie category
LaravelCookieConsent.acceptAll()
.then(() => document.getElementById('cookies-policy')?.remove());
// Accept essentials only
LaravelCookieConsent.acceptEssentials();
// Accept specific categories (checkbox form values)
const data = new FormData(document.querySelector('.cookies__customize'));
LaravelCookieConsent.configure(data);
// Reset consent — re-displays the modal
LaravelCookieConsent.reset();
```
--------------------------------
### Configure Laravel Cookie Consent
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
Customize the package's behavior by modifying the published configuration file. This includes settings for the consent cookie, API route prefix, and Google Analytics integration.
```php
// config/cookieconsent.php
use Illuminate\Support\Str;
return [
'url' => [
'domain' => null,
'middleware' => ['web'],
'prefix' => 'cookie-consent',
],
'cookie' => [
'name' => Str::slug(env('APP_NAME', 'laravel'), '_') . '_cookie_consent',
'duration' => 60 * 24 * 365, // 1 year in minutes
'domain' => '.mydomain.com', // Leading dot = shared across sub-domains
],
'policy' => 'cookie-policy', // Named route for Cookie Policy page link
'google_analytics' => [
'id' => env('GOOGLE_ANALYTICS_ID', ''),
'anonymize_ip' => env('GOOGLE_ANALYTICS_ANONYMIZE_IP', true),
],
];
```
--------------------------------
### CookiesServiceProvider::registerCookies()
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
The central method for declaring all cookies the application uses. It's called once per request by the package's service provider before the consent state is evaluated.
```APIDOC
## `CookiesServiceProvider::registerCookies()` — Registering Cookies
The central place to declare every cookie the application uses. Called once per request by the package's service provider before the consent state is evaluated.
```php
namespace App\Providers;
use Whitecube\LaravelCookieConsent\Consent;
use Whitecube\LaravelCookieConsent\Cookie;
use Whitecube\LaravelCookieConsent\Facades\Cookies;
use Whitecube\LaravelCookieConsent\CookiesServiceProvider as ServiceProvider;
use App\Services\DarkmodeService;
class CookiesServiceProvider extends ServiceProvider
{
protected function registerCookies(): void
{
// ── Essentials (always consented, cannot be opted out) ──────────────
Cookies::essentials()
->session() // Registers config('session.cookie')
->csrf(); // Registers XSRF-TOKEN
// ── Analytics (Google Analytics shorthand) ───────────────────────────
// Automatically registers _ga, _ga_ID, _gid, _gat cookies AND
// injects the gtag.js ');
});
// ── Chaining multiple cookies in one category ────────────────────────
Cookies::optional()
->cookie(fn(Cookie $c) => $c->name('ui_lang')->duration(525600)->description('Stores UI language preference.'))
->cookie(fn(Cookie $c) => $c->name('font_size')->duration(525600)->description('Stores chosen font size.'));
}
}
```
```
--------------------------------
### Blade Directives for Rendering Consent UI
Source: https://context7.com/whitecube/laravel-cookie-consent/llms.txt
These Blade directives allow you to easily integrate the cookie consent UI into your Laravel application's views. They require the `CookiesServiceProvider` to be registered.
```APIDOC
## Blade Directives — Rendering Consent UI
Four Blade directives integrate the consent UI into any layout. They require no configuration beyond the `CookiesServiceProvider` registration.
```blade
{{-- resources/views/layouts/app.blade.php --}}
@yield('title')
{{-- Loads the package JS (deferred) + any consented