chanondb/symfony7-cookie-consent-bundle
Installation:
composer require chanondb/symfony7-cookie-consent-bundle
npm i bootstrap --save-dev
Ensure bootstrap is installed for styling compatibility.
Enable Bundle:
Add to config/bundles.php:
Chanondb\CookieConsentBundle\CookieConsentBundle::class => ['all' => true],
Basic Configuration:
Create config/packages/cookie_consent.yaml with default settings:
cookie_consent:
categories:
- 'analytics'
- 'marketing'
- 'preferences'
First Use Case:
Trigger the consent modal by adding the Twig snippet to your base template (e.g., base.html.twig):
{{ cookie_consent() }}
This renders the Bootstrap 5-styled consent modal.
Dynamic Category Management:
Extend default categories in cookie_consent.yaml or via PHP:
cookie_consent:
categories:
- 'analytics'
- 'custom_category' # Add custom category
Use {{ cookie_consent_categories() }} in Twig to list all categories dynamically.
Route-Specific Exclusions:
Disable consent on specific routes (e.g., /privacy):
cookie_consent:
disabled_routes: ['privacy', 'imprint']
Override per-controller in PHP:
#[Route('/custom-page', name: 'custom_page', options: ['cookie_consent' => false])]
CSRF Protection:
Enable CSRF for form submissions (default: true):
cookie_consent:
csrf_protection: true
Ensure Symfony\UX\TwigComponent\Security\CsrfTokenGenerator is available.
XHR Request Handling: Configure a dedicated route for AJAX submissions:
cookie_consent:
form_action: 'cookie_consent_submit'
Create a route:
# config/routes.yaml
cookie_consent_submit:
path: /cookie-consent
controller: Chanondb\CookieConsentBundle\Controller\CookieConsentController::submit
Logging User Actions: Enable database logging:
cookie_consent:
use_logger: true
Requires a CookieConsent entity (see Extension Points).
Twig Extensions:
Use cookie_consent_is_accepted(), cookie_consent_get_categories() to conditionally load scripts/styles:
{% if cookie_consent_is_accepted('analytics') %}
{{ include('analytics_script.html.twig') }}
{% endif %}
JavaScript Integration: Listen for consent events via:
document.addEventListener('cookieConsentAccepted', (e) => {
console.log('Categories accepted:', e.detail.categories);
});
Laravel Adaptation:
Since this is a Symfony bundle, wrap it in a Laravel package (e.g., using spatie/symfony-bundle) or use its logic as a reference for a custom Laravel solution. Key takeaways:
session or cookie facade.public function handle($request, Closure $next) {
if (!$request->cookie('cookie_consent') && !$request->routeIs('cookie_consent')) {
return redirect()->route('cookie_consent.show');
}
return $next($request);
}
Symfony-Specific Dependencies:
HttpFoundation, SecurityBundle, and Twig. In Laravel:
Request with Laravel’s Illuminate\Http\Request.CsrfTokenManager with Laravel’s csrf_token() helper.Session::get() instead of Symfony’s session->get().Bootstrap 5 Conflicts:
webpack.mix.js to merge assets:
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
]);
CSRF Token Mismatch:
If csrf_protection: true fails, verify:
_csrf_token is passed in the form.security.csrf.token_manager).Route Name Collisions:
The form_action route must match exactly. Use absolute paths if needed:
form_action: '/cookie-consent/submit'
Database Logging:
use_logger: true, ensure the CookieConsent entity and migration exist. Adapt the Symfony entity to Laravel’s Eloquent:
// app/Models/CookieConsent.php
class CookieConsent extends Model {
protected $fillable = ['user_id', 'categories', 'accepted_at'];
}
Consent Not Showing:
bundles.php for the bundle’s inclusion.{{ cookie_consent() }} is in the Twig template.php bin/console cache:clear (Symfony) or php artisan cache:clear (Laravel).Cookies Not Setting:
http_only: false if testing locally (default: true).Application > Cookies) for cookie_consent_* cookies.CSRF Errors:
csrf_protection: false
Logger Not Working:
CookieConsent entity is registered in Symfony’s doctrine or Laravel’s Model.cookie_consents table.Custom Categories:
Extend the Category enum in PHP:
// src/Enum/CookieCategory.php
namespace App\Enum;
enum CookieCategory: string {
case Analytics = 'analytics';
case Custom = 'custom_category'; // Add new category
}
Update cookie_consent.yaml to include the new category.
Custom Storage: Override cookie storage by binding a custom service:
# config/services.yaml
services:
Chanondb\CookieConsentBundle\Storage\CookieStorage:
arguments:
$storage: '@app.custom_cookie_storage'
Implement CookieStorageInterface in Laravel:
class CustomCookieStorage implements CookieStorageInterface {
public function get($name) {
return cookie($name);
}
public function set($name, $value, $minutes) {
return response()->cookie($name, $value, $minutes);
}
}
Custom Templates:
Override Twig templates by copying from:
vendor/chanondb/symfony7-cookie-consent-bundle/resources/views/
to:
templates/bundles/cookieconsent/.
Event Listeners: Subscribe to consent events (Symfony):
// src/EventListener/CookieConsentListener.php
class CookieConsentListener implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
CookieConsentEvents::ACCEPTED => 'onConsentAccepted',
];
}
public function onConsentAccepted(CookieConsentEvent $event) {
// Log or trigger actions
}
}
In Laravel, use events or service providers to hook into consent logic.
Laravel-Specific Adaptations:
EventDispatcher with Laravel’s Event facade.Cookie facade for storage:
Cookie::queue('cookie_consent', $value, $minutes);
How can I help you explore Laravel packages today?