Laravel 12 – How to Add Cookie Consent Using Spatie
Laravel 12 – How to Add Cookie Consent Using Spatie
In this tutorial, we are going to discuss how to add a cookie consent banner in Laravel 12 using the Spatie package to ensure GDPR compliance and enhance user privacy on your Laravel application.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this guide, we set up a cookie consent banner in a Laravel 12 application using the Spatie Laravel Cookie Consent package. We begin by creating a new Laravel project and installing the package, followed by publishing its configuration to allow for customization. A route is defined to load a Blade view where the consent banner will be shown. The view file is created and styled to display the consent dialog. We also walk through how to adjust the banner text and appearance by publishing the translation and view files. Once everything is in place, we test the setup to ensure the banner displays correctly and remembers user consent.
Step # 1 : Set Up Your Laravel 12 Project.
To begin, either create a new Laravel 12 project or continue with your existing one. If Laravel is globally installed on your machine, you can use the following command to generate a new project.
laravel new cookie
Alternatively, if you’re using Composer, run.
composer create-project laravel/laravel --prefer-dist cookie
During the setup process, you'll be prompted to configure a few options. Here's how to proceed.
- Starter Kit: Select None. We’re starting with a minimal setup without any frontend scaffolding or authentication pre-installed.
- Database: Choose MySQL. This sets MySQL as the default database connection for the application.
- Run Migrations: Type yes. This will automatically create the default tables (such as users and password_resets) in your database.
- Would you like to run npm install and npm run build? Select yes to install frontend dependencies (like Vite and Tailwind) and compile the assets.
Once complete, you'll have a clean Laravel 12 project named cookie, ready to build on with MySQL as the database and essential frontend assets compiled.
Step # 2 : Navigate to Your Project Directory.
After creating the project, open your terminal (e.g., Git Bash, CMD, or Terminal on macOS/Linux) and move into your Laravel project directory. For example.
cd c:xampp/htdocs/cookie
Make sure you're inside the project folder so you can run Artisan commands and manage your application from the right location.
Step # 3 : Install Spatie's Cookie Consent Package.
Next, we’ll add cookie consent functionality using the Spatie Laravel Cookie Consent package. This package helps you display a customizable banner that informs users about cookie usage, useful for GDPR and other privacy regulations. To install it, run.
composer require spatie/laravel-cookie-consent
Once installed, the package is auto-registered, meaning you don’t need to manually add service providers or aliases. It comes with a ready-to-use Blade view for the cookie banner and manages user consent through cookies without extra setup.
Step # 4 : Publish the Configuration File.
To customize how the cookie consent banner looks and behaves, you’ll need to publish the package’s configuration file. This file lets you tweak options like the banner text, how long consent is remembered, and when the banner appears. Run the following Artisan command.
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-config"
After publishing, you’ll find a new file named cookie-consent.php in your config directory. You can edit this file to fine-tune the banner according to your app’s requirements, whether it’s changing the wording, modifying button labels, or adjusting visibility settings.
Step # 5 : Set Up a Route for the Homepage.
To test the cookie consent banner, let’s create a basic route that returns a view. Open the routes/web.php file and add.
Route::get('/', function () {
return view('master');
});
This route loads the master.blade.php view when users visit the root URL of your application. Make sure this view includes the necessary Blade directive to display the cookie banner, which we’ll cover shortly.
Step # 6 : Create a Homepage View.
Let’s set up a simple Blade view to serve as your homepage layout and to display the cookie consent banner. Inside the resources/views directory, create a new file called master.blade.php. This will be our base template for testing the banner integration. Here’s a sample layout you can use.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 12 - Code Shotcut - Spatie Cookie Consent</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
.js-cookie-consent {
@apply bg-white text-black border border-black rounded-md p-4 flex flex-col md:flex-row md:items-center md:justify-between gap-4 shadow-lg;
}
.js-cookie-consent-agree {
@apply bg-black text-white px-4 py-2 rounded-md hover:bg-gray-800 transition;
}
</style>
</head>
<body class="bg-gray-900 text-white pt-12 min-h-screen">
<div class="w-full max-w-2xl mx-auto px-6">
<h1 class="text-4xl font-bold mb-4 text-center">Master Blade</h1>
<p class="text-lg mb-8 text-center">Basic text for each page.</p>
<!-- Cookie Consent -->
@include('cookie-consent::index')
</div>
</body>
</html>
The important part is the @include('cookie-consent::index') line. This directive injects the consent banner provided by the Spatie package. You can place it wherever you'd like the banner to appear, typically somewhere near the bottom of your layout. This setup ensures the banner is shown properly when the page loads.
Step # 7 : Test the Cookie Consent Integration.
With everything configured, let’s verify that the cookie consent banner is working as expected. Start by launching the Laravel development server.
php artisan serve
Once the server is running, open your browser and visit: http://127.0.0.1:8000.
You should see your homepage along with a cookie consent banner at the bottom of the screen. When a user clicks Allow cookies, Laravel will store a cookie named laravel_cookie_consent, and the banner will automatically disappear. On future visits, the banner won’t appear again because consent has already been recorded.
Customizing the Banner Text
If you want to change the wording shown on the banner (for example, to match your brand tone or provide additional context), you’ll need to publish the translation files.
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-translations"
This will create a translation file at cookie/lang/vendor/cookie-consent/en/texts.php you can now customize the messages.
<?php
return [
'message' => 'Custom Text : Your experience on this site will be improved by allowing cookies.',
'agree' => 'Allow cookies',
];
If you want to see your changes immediately, delete the browser cookie manually and refresh the page.
Full Control Over the Banner Layout
If you’d like to tweak the structure or style of the cookie banner beyond the text, you can publish the view files.
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-views"
This command copies the Blade views to resources/views/vendor/cookie-consent/. Inside that folder, you’ll find the dialogContents.blade.php file. You can customize this file to change the layout, HTML structure, or add additional styles or elements as needed. This gives you full flexibility over both the appearance and behavior of your cookie consent dialog.
Conclusion
By following these steps, we've successfully implemented the Spatie Laravel Cookie Consent package in our Laravel 12 application. Starting from project setup, we installed and configured the package to display a customizable cookie consent banner. We published the necessary configuration and translation files, defined a route, created a view, and tested the functionality to ensure everything works smoothly. We also explored options to personalize the banner’s text and structure, giving us full control over its appearance and behavior. With this setup, your Laravel 12 application is now equipped to manage cookie consent effectively, ensuring compliance with privacy regulations while providing a better user experience.
For more details, please refer to the official Spatie Cookie Consent documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments