Adding cookie consent to your Laravel site in under 5 minutes
Implement a cookie consent package and stay GDPR compliant in a few easy steps
You will no doubt be very aware of the cookie consent banners that started appearing on websites a few years ago as a result of EU legislation, and which seem to have become even more prevalent since the arrival of GDPR in Europe.
We’ve had a few customers request the addition of these banners to their sites, and depending on the technology behind the website and the customisation requirements this can be a very quick task or it can take a reasonable amount of time to implement properly.
The package is installed with composer, just use:
composer require spatie/laravel-cookie-consent
That’s it for the installation part, easy huh? 🚀
To publish the configuration file, (optional) use:
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="config"
You can enable or disable the cookie consent bar, change the name of the cookie and set its life from these settings, but the defaults are likely to be fine for most people, so you can probably skip this step.
To publish the language files to change the message and button text, use:
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="lang"
You’ll find the language files in:
The default message is “Your experience on this site will be improved by allowing cookies.” and the button text is: “Allow cookies”, so again if you’re happy with this then feel free to skip this step too.
To publish the views used for the cookie consent bar itself, use:
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="views"
You’ll find the view files in:
You can add extra classes if required to any of the elements here, for example if you’re using Bootstrap 4, you can add
btn btn-sm btn-primary to the
<button> classes and
fixed-bottom bg-success p-2 text-light text-center to the main
<div class="js-cookie-consent cookie-consent"> in
This will create the bar like you see on welcm.uk — fixed to the bottom of the screen with a small blue button and centered white text.
In your blade template, simply add:
Typically you would add this in your layout file so it appears on all pages, but you can choose to display it only on specific pages or use
@if blade directives to set your own logic for when the bar is displayed.
That’s it! You should now have a fully functioning and customised cookie consent banner on your Laravel site in under 5 minutes!
We’re happy to help with all aspects of Laravel development so if we can help with this or anything else for your website or app, feel free to get in touch!
Like this story? Please follow us on Twitter.
At Welcm we design, develop and support touch screen applications and systems.
We also make Visitor Management Easy at https://welcm.ly
Originally published at welcm.uk.