Laravel 11 - Spatie Cookie Consent
Laravel 11 - Spatie Cookie Consent
In this tutorial, we'll explore how to implement Spatie Cookie Consent for the EU in Laravel 11, ensuring compliance with GDPR by managing cookie usage transparently.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide walks you through setting up and displaying a cookie consent banner in a Laravel application using the Spatie Laravel Cookie Consent package. The process begins by creating a new Laravel project and configuring it with MySQL for the database. After installing the Spatie Cookie Consent package, we publish its configuration file for customization. We then define a route to display the master view, set up the necessary Blade file, and customize the view for cookie consent. To ensure the package works correctly, we also explore how to modify dialog text and layout. Finally, we verify the functionality by testing the server and confirming the banner appears and behaves as expected.
Step # 1 : Create a Fresh Laravel Project or Use an Existing One.
To get started, we’ll create a new Laravel project. If you already have an existing project, you can skip this step. If Laravel is installed globally you can use the below command.
laravel new cookie
Or use Composer by running the command.
composer create-project laravel/laravel --prefer-dist cookie
During the setup process, select the following options.
- Starter Kit: Choose None.
- Testing Framework: Select Pest.
- Database: Opt for MySQL.
- Migrations: When prompted, type yes to run the default migrations.
This gives you a clean Laravel project named cookie, configured with Pest for testing and MySQL as the database.
Step # 2 : Access the project.
Once the project is set up, open your terminal (e.g., Git Bash) and navigate to your Laravel project’s root directory. For example.
cd c:xampp/htdocs/cookie
This ensures you're inside the correct folder to start working on your project.
Step # 3 : Install the Spatie Cookie Consent package.
To add the cookie consent functionality to your Laravel application, we need to install the Spatie Cookie Consent package. This package provides a simple way to show a cookie consent banner that complies with various regulations (such as GDPR). It includes default views and the necessary logic to handle user consent, allowing you to easily display and manage cookie notifications. Run the following command to install the package.
composer require spatie/laravel-cookie-consent
Once installed, the package will automatically register itself, so there is no need for any additional setup. The package includes a pre-built view for displaying the cookie consent banner and handles cookie storage for remembering the user's choice.
Step # 4 : Publish the configuration.
To customize the default settings of the Spatie Cookie Consent package, we need to publish its configuration file. This file allows you to adjust various settings of the cookie consent banner, such as its text, appearance, and behavior, enabling you to tailor it to your application’s needs. Run the following command to publish the configuration.
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-config"
This command will create a configuration file in your config directory. In this file, you can adjust settings such as the cookie expiration time, the text displayed on the banner, and whether the banner should be shown on page load or only after certain actions.
Step # 5 : Update the Route.
Now, let’s define the route that will load the view. In this example, we’ll ensure that when users visit the homepage, they see the master view. Open your web.php file and define the route like so.
Route::get('/', function () {
return view('master');
});
This will direct users to the master view when they visit the homepage.
Step # 6 : Create a View.
Now let’s create the view for the homepage. Inside the resources/views folder, create a file named master.blade.php. This will be the layout where we display the cookie consent banner. Add the following content to master.blade.php for testing purposes.
<!doctype html>
<html>
<head>
<title>Laravel 11 - Spatie Cookie Consent - Code Shotcut</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<style type="text/css">
.js-cookie-consent{
background-color: white;
color: black;
border: 1px solid black;
border-radius: 5px;
}
.js-cookie-consent-agree{
background-color: black;
color: white;
}
</style>
</head>
<body class="bg-dark text-white">
<div class="container mt-5">
<div class="row">
<div class="col-12 mt-5">
<h1>Master Blade</h1>
<p>Basic text for each page.</p>
</div>
</div>
<!--To display the dialog all you have to do is include this view in your template -->
@include('cookie-consent::index')
</div>
</body>
</html>
In this Blade template, the cookie consent banner will appear on all pages where @include('cookie-consent::index') is used.
Step # 7 : It's time to test.
Now that everything is set up, it’s time to test. Start the Laravel development server by running this command.
php artisan serve
Then, open your browser and visit: 127.0.0.1:8000.
When you first visit the site, the cookie consent banner will be displayed. If you click Allow cookies, a laravel_cookie_consent cookie will be set, and the dialog will disappear. On the next visit, the banner will not appear again, as the consent has already been given.
Customizing the dialog text
If you'd like to modify the text displayed in the cookie consent dialog, you can do so by publishing the translation files. Use the following command.
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-translations"
This will publish the translation file to: resources/lang/vendor/cookie-consent/en/texts.php. You can update the message in this file, like so.
<?php
return [
'message' => 'Custom Text : Your experience on this site will be improved by allowing cookies.',
'agree' => 'Allow cookies',
];
Delete the cookie manually and reload the page.
Customizing the dialog contents
If you need full control over the content of the dialog, you can publish the views of the package with this command.
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-views"
This will copy the necessary view files to: resources/views/vendor/cookie-consent. You can modify the dialogContents view if you need to make changes to the structure or appearance of the consent dialog.
Conclusion
By following these steps, we've successfully integrated the Spatie Laravel Cookie Consent package into our Laravel project, ensuring compliance with cookie laws. We created a fresh Laravel project, installed and configured the package, and customized the cookie consent banner's text and layout to suit our needs. This process included publishing configuration files, setting up a route and view, and testing the functionality to ensure the cookie consent dialog appears and behaves as expected. Additionally, we explored how to customize the dialog’s text, appearance, and even the entire content, giving us full control over how users interact with the cookie consent feature. With this integration in place, your Laravel application is now prepared for cookie consent handling, enhancing both legal compliance and user experience.
For more details, you can refer to the Spatie Laravel Cookie Consent package 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