Laravel 12 - How to Integrate Newsletter Using Spatie and Mailchimp.
Laravel 12 - How to Integrate Newsletter Using Spatie and Mailchimp.
In this tutorial, we will learn how to integrate a newsletter in Laravel 12 using Spatie Newsletter and Mailchimp, handle subscriptions, validate emails, and display success or error messages.
Quick Overview
This guide walks you through adding newsletter subscription functionality to a Laravel application using the Spatie Newsletter package and Mailchimp API. After setting up a fresh Laravel project, the necessary packages are installed and configured. A controller is created to manage subscription logic, including email validation and handling success or error messages. Routes and views are defined for the subscription form, and the system is tested on the local server. The result is a working newsletter system integrated seamlessly into your Laravel project.
Step # 1 : Initialize Your Laravel 12 Project.
To begin, you can either set up a brand-new Laravel project or continue working with an existing application. If you prefer creating a new project named newsletter using the global Laravel Installer (make sure it is installed globally on your system), run the following command.
laravel new newsletter
Alternatively, you may create the project using Composer without relying on the global Installer.
composer create-project laravel/laravel --prefer-dist newsletter
When installing via Composer, Laravel provides a clean and minimal default setup. However, if you use the Laravel Installer, it will walk you through a short interactive configuration. During this process, choose the following options.
- Starter kit installation: Select none when asked if you would like to install a starter kit.
- Testing framework: Choose Pest.
- Database selection: Select mysql for your application.
- Run default migrations: Choose yes so the initial database tables are created automatically.
- Frontend dependency: When prompted, type yes to allow Laravel to run npm install and npm run build. This will automatically install and compile all required frontend dependencies.
After the installation completes, your new Laravel 12 application named newsletter will be ready to use, with everything configured based on the options you selected during the setup process.
Step # 2 : Open the Newsletter project directory.
Launch a terminal application (for example, Git Bash or Command Prompt) and move to the root folder of your Laravel project by running the following command.
cd c:xampp/htdocs/newsletter
Once you run the command, your terminal will point to the newsletter project’s root directory, allowing you to execute Artisan commands, manage dependencies, and continue building your Laravel 12 application from the correct location.
Step # 3 : Install the Newsletter Package.
To add newsletter functionality to your Laravel project, run the following Composer command to install the spatie/laravel-newsletter package.
composer require spatie/laravel-newsletter
The spatie/laravel-newsletter package makes it easy to manage newsletter subscriptions, connect with services like Mailchimp, and handle mailing lists directly from your Laravel project making newsletter management straightforward and efficient.
Step # 4 : Publish and Configure the Newsletter Settings.
To make the configuration file for the Newsletter package available, run the following Artisan command.
php artisan vendor:publish --tag="newsletter-config"
This will create a newsletter.php file inside the config directory. Here, you can customize settings such as API keys and other preferences for the package.
Next, open the newsletter.php file to update the configuration. Since we’ll be using Mailchimp to manage our newsletter, change the driver from Mailcoach to Mailchimp.
// From
'driver' => env('NEWSLETTER_DRIVER', Spatie\Newsletter\Drivers\MailcoachDriver::class),
// To
'driver' => env('NEWSLETTER_DRIVER', Spatie\Newsletter\Drivers\MailChimpDriver::class),
Also, update the driver_arguments section for the endpoint configuration.
// From
'driver_arguments' => [
'api_key' => env('NEWSLETTER_API_KEY'),
'endpoint' => env('NEWSLETTER_ENDPOINT'),
],
// To
'driver_arguments' => [
'api_key' => env('NEWSLETTER_API_KEY'),
'endpoint' => env('NEWSLETTER_ENDPOINT', null),
],
These changes ensure that the package is correctly set up to work with Mailchimp for managing your newsletter subscriptions.
Step # 5 : Install and Configure the Mailchimp Package.
To connect your Laravel application with Mailchimp, you first need to install the Mailchimp API package using Composer.
composer require drewm/mailchimp-api
Next, gather your Mailchimp credentials.
- Create a Mailchimp Account: If you don’t have one already, sign up at Mailchimp (https://mailchimp.com/) and log in. You’ll be taken to the Dashboard after signing in.
- Generate an API Key: Click your profile name in the top navigation bar, select Profile, then go to Extras -> API keys. Click Create A Key to generate a new API key. Make sure to save it securely, as you won’t be able to view it again.
- Find your List ID (Audience ID): In the left-hand menu, go to Audience, then click More Options -> Audience Settings. Your Audience ID (List ID) will be displayed there.
Finally, update your .env file to store these credentials securely. Add the following lines, replacing the placeholders with your actual API key and List ID.
NEWSLETTER_API_KEY="Your API Key Here"
NEWSLETTER_LIST_ID="Your List ID Here"
Once your API key and List ID are set in the .env file, your Laravel 12 application will be fully connected to Mailchimp, ready to handle newsletter subscriptions and manage your mailing lists seamlessly.
Step # 6 : Create the Newsletter Controller.
To manage newsletter subscriptions, you need a dedicated controller. Generate it by running the following Artisan command.
php artisan make:controller NewsletterController
Once the controller is created, open NewsletterController.php and replace its content with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Newsletter;
class NewsletterController extends Controller
{
// Display the subscription form
public function index()
{
return view('form');
}
// Handle newsletter subscription
public function subscribe(Request $request)
{
// Validate email input
$request->validate([
'email' => 'required|email',
]);
$email = $request->email;
try {
// Check if the email is already subscribed
if (Newsletter::isSubscribed($email)) {
return redirect()->back()
->with('error', 'You have already subscribed to our newsletters.')
->withInput();
}
// Try subscribing the email
$subscribed = Newsletter::subscribe($email);
if ($subscribed) {
return redirect()->back()
->with('success', 'You have successfully subscribed to our newsletters.')
->withInput();
} else {
// Mailchimp rejected the subscription for some reason
return redirect()->back()
->with('error', 'Subscription failed. Please check your email or try again later.')
->withInput();
}
} catch (\Exception $e) {
// Catch any exceptions (like forgotten/deleted emails)
return redirect()->back()
->with('error', 'Subscription failed: ' . $e->getMessage())
->withInput();
}
}
}
The controller manages the subscription form and processes incoming email subscriptions. It ensures emails are valid, prevents duplicate subscriptions, adds new subscribers, and delivers clear success or error messages to the user.
Step # 7 : Set Up Routes for the Newsletter.
First, import the NewsletterController at the top of your routes/web.php file.
use App\Http\Controllers\NewsletterController;
Next, update your routes to handle both displaying the form and processing subscriptions.
// Display the newsletter subscription form on the homepage
Route::get('/', [NewsletterController::class, 'index']);
// Handle the form submission and subscribe the email to the newsletter
Route::post('/subscribe', [NewsletterController::class, 'subscribe']);
The GET route (/) will display the subscription form on your homepage, allowing users to enter their email. The POST route (/subscribe) will handle the form submission, validate the input, and add the email to your Mailchimp list if it’s valid and not already subscribed.
Step # 8 : Create a view.
Create a form.blade.php file with a form where users can enter their email to subscribe. The form will also show messages if the subscription is successful or if there is an error.
<!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 Newsletter</title>
<!-- Tailwind CSS CDN for styling -->
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-gray-100 flex items-center justify-center min-h-screen">
<div class="w-full max-w-xl p-8 bg-gray-800 rounded-xl shadow-lg">
<h2 class="text-3xl font-bold text-center mb-6 text-indigo-400">Join Our Newsletter</h2>
<p class="text-center text-gray-400 mb-6">Subscribe to get the latest updates directly in your inbox.</p>
<!-- Newsletter subscription form -->
<form action="{{ url('/subscribe') }}" method="post" class="space-y-4">
@csrf
<div>
<label for="email" class="block text-sm font-medium text-gray-300">Email Address</label>
<input type="email" name="email" id="email" placeholder="you@example.com"
value="{{ old('email') }}"
class="mt-2 w-full px-4 py-3 bg-gray-700 border border-gray-600 rounded-md text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500">
<small class="block text-xs text-gray-500 mt-1">We respect your privacy. No spam, ever.</small>
<!-- Display error message if subscription fails -->
@if(session()->has('error'))
<div class="mt-2 text-sm text-red-500">
{{ session()->get('error') }}
</div>
@endif
<!-- Display success message if subscription succeeds -->
@if(session()->has('success'))
<div class="mt-2 text-sm text-green-500">
{{ session()->get('success') }}
</div>
@endif
</div>
<!-- Submit button -->
<button type="submit"
class="w-full py-3 bg-indigo-500 hover:bg-indigo-600 text-white font-semibold rounded-md transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-indigo-400">
Subscribe Now
</button>
</form>
<p class="text-center text-gray-500 mt-6 text-xs">© {{ date('Y') }} Code Shotcut. All rights reserved.</p>
</div>
</body>
</html>
This view works with your controller and routes to handle the newsletter logic. It validates the email input, prevents duplicate subscriptions, and shows clear success or error messages after the form is submitted.
Step # 9 : Test the Newsletter Functionality.
Start the Laravel development server by running.
php artisan serve
Next, open your browser and go to: http://127.0.0.1:8000. Try subscribing a user by entering their email. If the user is not previously subscribed, the system will add the email to the newsletter list and display a success message.
If the user is already subscribed, the system will notify them with an appropriate error message.
Conclusion
By following this guide, we have successfully integrated a newsletter subscription system into a Laravel 12 application. We set up a fresh Laravel project, installed and configured the Spatie Newsletter package along with the Mailchimp API, created a controller to handle subscriptions, defined routes and views for the subscription form, and tested the system on a local server. This implementation provides a working foundation for managing newsletter subscriptions, which can be expanded with additional features as needed.
For more details, refer to the Spatie Newsletter 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