Laravel 10 - Newsletters

Touseef Afridi
12 Sep 24

Laravel 10 - Newsletters

In this tutorial, we will discuss how to implement a newsletter in Laravel 10. Newsletters helps automate email communication, keeping subscribers informed and engaged, improving audience reach and retention.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide will take you through the steps to integrate a newsletter subscription feature into your Laravel application. You’ll begin by setting up a fresh Laravel project, then proceed to install and configure the Spatie Newsletter package, linking it to Mailchimp for efficient subscription management. The process includes creating a controller to manage subscriptions, validating user emails, and displaying feedback messages. A clean subscription form built with Bootstrap will be implemented, along with necessary route configurations. Finally, you’ll test the setup to ensure smooth user interaction for subscribing to your newsletter.

Step # 1 : Create a New Laravel Project.

Kick things off by creating a brand-new Laravel project. You can do this using either the Laravel installer or Composer whichever works best for you. Use the following command if you have Laravel globally installed.
laravel new newsletter
Or use Composer.
composer create-project laravel/laravel --prefer-dist newsletter
This step sets up a fresh Laravel environment named newsletter. It's the foundation of your entire application, where all your newsletter functionality will be built. Make sure everything installs properly before moving on.

Step # 2 : Access the Project Directory.

Open your terminal (like Git Bash or CMD) and navigate to the root folder of your Laravel project. Example
cd c:xampp/htdocs/newsletter
Now, install front-end dependencies and start the Vite development server.
npm install && npm run dev
Keep this terminal running. Open a new terminal window or tab, navigate to the same project folder, and use it to run your Laravel commands.

Step # 3 : Install the Laravel Newsletter Package.

Run the following command to install the newsletter package via Composer.
composer require spatie/laravel-newsletter
This package, developed by Spatie, provides a simple and elegant way to manage newsletter subscriptions in your Laravel application. It acts as a wrapper around services like Mailchimp, making it easy to subscribe users, check subscription status, and manage lists without dealing directly with complex API calls.

Step # 4 : Publish and Configure the Newsletter Settings.

To make the newsletter package configurable, run this command.
php artisan vendor:publish --tag="newsletter-config"
This will create a new file named newsletter.php inside the config directory. Open this file and make a couple of important changes. First, update the default driver from Mailcoach to Mailchimp by replacing.
'driver' => env('NEWSLETTER_DRIVER', Spatie\Newsletter\Drivers\MailcoachDriver::class),
to
'driver' => env('NEWSLETTER_DRIVER', Spatie\Newsletter\Drivers\MailChimpDriver::class),
Next, tweak the driver_arguments array so the endpoint value falls back to null if it's not set in the environment file. Update it 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 tell the package to use Mailchimp as the driver and set it up to securely pull your API credentials from the environment file. This keeps your sensitive information safe and your configuration clean.

Step # 5 : Connect Your Laravel App to Mailchimp.

To link your Laravel project with Mailchimp, start by installing the Mailchimp API package using Composer. Run the following command.
composer require drewm/mailchimp-api
After installing the package, you'll need to grab your Mailchimp API Key and Audience ID.
  1. Create a Mailchimp Account: If you don’t already have one, head over to https://mailchimp.com/ and sign up. Once you’re logged in, you'll be taken to your dashboard.
  2. Get Your API Key: Click your profile icon in the top right corner, go to Account, then navigate to Extras > API keys. Click Create A Key to generate one. Be sure to copy and store it somewhere safe, as it won’t be shown again.
  3. Get Your Audience ID: From the sidebar, click Audience > All Contacts, then go to Settings. Your Audience ID (also referred to as the List ID) will be displayed there.

Open your project’s .env file and add the following variables using your actual Mailchimp credentials.
NEWSLETTER_API_KEY="Your API Key Here"
NEWSLETTER_LIST_ID="Your List ID Here"
This step completes the Mailchimp integration setup for your Laravel app.

Step # 6 : Generate the Newsletter Controller.

To handle newsletter subscriptions, you’ll need a dedicated controller. Use the following Artisan command to create it.
php artisan make:controller NewsletterController
Once the controller is generated, open the newly created NewsletterController.php located in app/Http/Controllers and replace its contents with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Newsletter;
class NewsletterController extends Controller
{
    // Displays the form view
    public function index()
    {
        return view('form');
    }
    // Handles the subscription process
    public function subscribe(Request $request)
    {
        // Validates email field
        $request->validate([
            'email' => 'required|email',
        ]);
        try {
            // Checks if the email is already subscribed to the newsletter
            if (Newsletter::isSubscribed($request->email)) {
                // Redirects back with an error message if the email is already subscribed
                return redirect()->back()->with('error', 'You have already subscribed to our Newsletters.');
            } else {
                // Subscribes the email to the newsletter
                Newsletter::subscribe($request->email);
                // Redirects back with a success message once subscribed
                return redirect()->back()->with('success', 'You have successfully subscribed to our Newsletters.');
            }
        } catch (Exception $e) {
            // If an error occurs, catch the exception and show the error message
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
This controller handles two tasks. It displays the subscription form through the index method, and it processes form submissions via the subscribe method, which validates the email, checks if it's already subscribed using the Spatie Newsletter facade, and either returns an error or adds the email to your Mailchimp list.

Step # 7 : Set Up the Routes.

In this step, you’ll connect your controller to the web routes so users can access the newsletter form and submit their subscription. First, import the NewsletterController at the top of your routes/web.php file.
use App\Http\Controllers\NewsletterController;
Then, define the routes by updating the default homepage route to load the form, and add a new POST route to handle form submissions.
//Update the default route and create a new route to submit the form.
Route::get('/', [NewsletterController::class, 'index']);
Route::post('/subscribe', [NewsletterController::class, 'subscribe']);
The GET route displays the subscription form, while the POST route processes the submitted email address.

Step # 8 : Build the Subscription Form View.

Next, you need to create a user interface where visitors can enter their email to subscribe. To do this, create a Blade view file named form.blade.php inside the resources/views directory, and paste the following HTML code into it.
<!DOCTYPE html>
<html>
<head>
 <title>Laravel Newsletter - Code Shotcut</title>
</head>
<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>
<body>
 <div class="container mt-5 bg-dark text-white">
  <div class="row">
   <div class="col-6 offset-3 mt-5 mb-5">
    <form action="{{ url('/subscribe') }}" method="post">
     @csrf
     <div class="form-group">
      <label for="exampleInputEmail1">SUBSCRIBE TO NEWSLETTER</label>
      <input type="email" name="email" class="form-control" placeholder="Enter email">
      <small id="emailHelp" class="form-text text-white">We'll never share your email with anyone else.</small>
      @if(session()->has('error'))
      <div class="alert alert-danger">
       {{ session()->get('error') }}
      </div>
      @endif
      @if(session()->has('success'))
      <div class="alert alert-success">
       {{ session()->get('success') }}
      </div>
      @endif
     </div>
     <button type="submit" class="btn btn-primary">Subscribe</button>
    </form>
   </div>
  </div>
 </div>
</body>
</html>
The form is built using Bootstrap 4 to give it a clean and responsive layout. It includes an input field where users can enter their email address and submit it to subscribe to the newsletter. After submission, the system provides immediate feedback through alert messages either confirming the subscription or notifying the user if the email is already registered. The design ensures a smooth user experience with a straightforward and professional interface.

Step # 9 : Testing the Setup.

To begin testing, launch the Laravel development server by running.
php artisan serve
Once the server is running, open your browser and visit the following address: 127.0.0.1:8000. Attempt to subscribe a user by entering their email address.

If the email is already subscribed, the system will show a message like You have already subscribed to our Newsletters.



You can also view the subscriber emails directly in your Mailchimp account to confirm the subscriptions.

Conclusion

By following this guide, you’ve successfully integrated a newsletter subscription system into your Laravel application, enabling efficient subscription management through Mailchimp. With the Spatie Newsletter package, you now have a clean, user-friendly interface for managing subscriptions and providing feedback to users. This setup streamlines the process of collecting and managing subscriber emails, allowing you to focus on growing your audience without worrying about technical complexities.
For more details, refer to the official documentation of the Spatie Newsletter package for advanced features and customization options.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering